我有以下组件:
@Component({
selector: 'my-form',
templateUrl: './my-form.component.html',
})
export class MyFormComponent implements OnInit {
@Input('company') company: CompanyInfo;
private config: ConfigInterface | null;
constructor(private companyService: CompanyService, private something: Something, private dialog: MatDialog) {
}
ngOnInit() {
....
}
theMtehodWhichIWantToTest(company: string) {
if (someTest.indexOf(domain)) {
this.dialog.open(MyAllertComponent, {
data: {
title: 'blah',
},
});
}
}
}
我糟糕且失败的单元测试:
describe( 'MyFormComp', () => {
it('should open MatDialog if email is from popular domain', () => {
const dialog = {} as MatDialog;
const comp = new MyComponent({} as CompanyService, {} as Something, dialog);
comp.getCompanys(company);
expect(dialog.open(AlertComponent));
});
})
错误信息: TypeError: dialog.open is not a function
是的,我知道为什么我会收到此错误消息 - 我没有正确模拟对话框并且函数open
不可用。有人可以告诉我如何open
使用茉莉花(即如何正确模拟 MatDialog?)
我对 js 单元测试很陌生,所以,只是告诉我 google 什么对我来说不会很有帮助。
您可以使用 beforeEach 方法为您的组件依赖项创建间谍:
emailServiceSpy = jasmine.createSpyObj('EmailService', {});
somethingSpy = jasmine.createSpyObj('Something', {});
dialogSpy = jasmine.createSpyObj('MatDialog', ['open']);
然后为您的测试模块提供这些:
TestBed.configureTestingModule({
declarations: [YourComponent],
providers: [
{ provide: EmailService, useValue: emailServiceSpy },
{ provide: Something, useValue: somethingSpy },
{ provide: MatDialog, useValue: dialogSpy },
],
imports: [],
}).compileComponents();
在您的测试中,您可以检查您的 spy-function 是否被调用:
expect(dialogSpy.open).toHaveBeenCalled();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句