我有以下内容:
@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
不可用。有人可以告诉我如何使用jasmine使open
可用(即如何正确模拟MatDialog吗?)
我对js单元测试来说还是一个新手,所以,仅告诉我对Google的了解对我不是很有帮助。
答案 0 :(得分:1)
您可以使用beforeEach方法为组件依赖项创建间谍:
emailServiceSpy = jasmine.createSpyObj('EmailService', {});
somethingSpy = jasmine.createSpyObj('Something', {});
dialogSpy = jasmine.createSpyObj('MatDialog', ['open']);
然后为您的Testmoudle提供这些内容:
TestBed.configureTestingModule({
declarations: [YourComponent],
providers: [
{ provide: EmailService, useValue: emailServiceSpy },
{ provide: Something, useValue: somethingSpy },
{ provide: MatDialog, useValue: dialogSpy },
],
imports: [],
}).compileComponents();
在测试中,您可以检查间谍功能是否被调用:
expect(dialogSpy.open).toHaveBeenCalled();