茉莉花:测试嵌套函数是否被调用

时间:2019-04-02 07:44:20

标签: angular karma-jasmine

我是编写单元测试用例的新手,

以下是我的服务

  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方法。

这怎么办?请帮忙。

1 个答案:

答案 0 :(得分:0)

我认为您在第二个测试用例/间谍定义中有错字,我想您想侦察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();
});