gpt4 book ai didi

javascript - MatDialog 服务单元测试 Angular 6 错误

转载 作者:数据小太阳 更新时间:2023-10-29 04:59:45 25 4
gpt4 key购买 nike

我有模式服务来打开、确认和关闭对话框,我正在制作它的单元测试文件,但我在 Angular 上遇到错误,这是代码。

modal.service.ts

@Injectable()
export class ModalService {

constructor(private dialog: MatDialog) { }

public open<modalType>(modalComponent: ComponentType<modalType>): Observable<any> {
let dialogRef: MatDialogRef<any>;

dialogRef = this.dialog.open(modalComponent, {
maxWidth: '100vw'
});
console.log(dialogRef)
dialogRef.componentInstance.body = body;

return dialogRef.afterClosed().pipe(map(result => console.log('test'); );
}

}

modal.service.spec.ts

export class TestComponent  {}


describe('ModalService', () => {
let modalService: ModalService;

const mockDialogRef = {
open: jasmine.createSpy('open')
};

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ MatDialogModule ],
providers: [
ModalService,
MatDialogRef,
{ provide: MatDialog, useClass: MatDialogStub }
]
}).compileComponents();

modalService = TestBed.get(ModalService);
}));


it('open modal', () => {
modalService.open(DummyComponent, '300px');
expect(modalService.open).toHaveBeenCalled();

});

});

所以对于那个代码,错误是

TypeError: Cannot read property 'componentInstance' of undefined

你能帮我看看如何让它成功吗?非常感谢您的帮助。

最佳答案

测试 mat-dialogs 可能很棘手。我倾向于使用 spy 对象从打开的对话框(下面的 dialogRefSpyObj)返回,这样我可以更轻松地跟踪和控制测试。在您的情况下,它可能类似于以下内容:

describe('ModalService', () => {
let modalService: ModalService;
let dialogSpy: jasmine.Spy;
let dialogRefSpyObj = jasmine.createSpyObj({ afterClosed : of({}), close: null });
dialogRefSpyObj.componentInstance = { body: '' }; // attach componentInstance to the spy object...

beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatDialogModule],
providers: [ModalService]
});
modalService = TestBed.get(ModalService);
});

beforeEach(() => {
dialogSpy = spyOn(TestBed.get(MatDialog), 'open').and.returnValue(dialogRefSpyObj);
});

it('open modal ', () => {
modalService.open(TestComponent, '300px');
expect(dialogSpy).toHaveBeenCalled();

// You can also do things with this like:
expect(dialogSpy).toHaveBeenCalledWith(TestComponent, { maxWidth: '100vw' });

// and ...
expect(dialogRefSpyObj.afterClosed).toHaveBeenCalled();
});
});

关于javascript - MatDialog 服务单元测试 Angular 6 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52993583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com