我是编写单元测试用例的新手,
以下是我的服务,
createComponent(content, type) {
if (!type) {
this.redirect();
}
this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(type);
this.componentReference = this.rootViewContainer.createComponent(this.componentFactory);
this.componentReference.instance.contentOnCreate(content);
}
redirect() {
return this.router.navigate(['/information']);
}
我的服务规范,
it('should call createComponent ', () => {
spyOn(renderEngineService, 'createComponent');
renderEngineService.setRootViewContainerRef(oneColumnTemplateComponent.view);
renderEngineService.createComponent(oneColumnTemplateComponent.content, 'HeadingComponent');
expect(renderEngineService.createComponent).toHaveBeenCalled();
});
it('should call redirect ', () => {
spyOn(renderEngineService, 'createComponent');
renderEngineService.setRootViewContainerRef(oneColumnTemplateComponent.view);
renderEngineService.createComponent(oneColumnTemplateComponent.content, 'UndefinedComponent');
expect(renderEngineService.redirect).toHaveBeenCalled();
});
我想测试,如果createComponent
无效,它应该调用redirect
方法。
如何才能做到这一点 ?请帮忙。
我认为你的第二个测试用例/间谍定义中有一个拼写错误,我想你想监视redirect
而不是createComponent
。你也想嘲笑createComponent
电话或让它通过并检查它是否被调用?根据不同,测试用例必须写得有点不同。
无论如何,我会将其更改为以下内容(如果您打算不嘲笑createComponent
调用):
it('should call createComponent ', () => {
// add callThrough if you want the actual function to be called, otherwise remove it
let spy = spyOn(renderEngineService, 'createComponent').and.callThrough();
renderEngineService.setRootViewContainerRef(oneColumnTemplateComponent.view);
renderEngineService.createComponent(oneColumnTemplateComponent.content, 'HeadingComponent');
expect(spy).toHaveBeenCalled();
});
it('should call redirect ', () => {
// spy on redirect here, not createComponent
let spy = spyOn(renderEngineService, 'redirect');
renderEngineService.setRootViewContainerRef(oneColumnTemplateComponent.view);
// pass null as second argument, otherwise redirect will not be called
renderEngineService.createComponent(oneColumnTemplateComponent.content, null);
expect(spy).toHaveBeenCalled();
});