首页 > 解决方案 > Angular + Jasmine:如何忽略/模拟测试组件中的一个函数(不在依赖项中)?

问题描述

我知道如何从依赖项中模拟一个函数,但现在我有一个不在依赖项中的函数,它在我想要测试的实际组件中。我怎么能告诉茉莉花简单地忽略它?

当我运行ng test此测试失败时:

在此处输入图像描述

原因是我从外部库导入的这个函数:

import { documentToHtmlString } from '@contentful/rich-text-html-renderer';

(Contentful 是我在项目中使用的内容管理服务。)

在我的组件中,这里调用了这个函数:

ngOnInit() {
  
  //the next line keeps the test from creating, I don't really care to test this function, how can I mock it?:
  this.serializeContentfulRichText(someContentfulTextDoesntMatter);
  
  // a lot more stuff that I actually need to test
  ...
}

serializeContentfulRichText(contentfulText: any) {
    return documentToHtmlString(contentfulText, this.myRenderingOptions);
}

当我删除该documentToHtmlString行并返回 null 时,其余的测试工作,我可以测试我的整个组件。但当然我不能只在我的实际组件中删除这一行,我只想在我的测试中忽略/模拟它。

我用间谍试了一下:

it('should create', () => {
    let spy = spyOn(component, 'serializeContentfulRichText')
    expect(spy).toHaveBeenCalledTimes(1)
    expect(component).toBeTruthy();
  });

但是间谍没有被调用并且组件没有被创建(两个期望都失败了)。

标签: angularunit-testingmockingjasminecontentful

解决方案


如果要存根测试组件的方法,则需要在 之后TestBed.createComponent但在 之前进行fixture.detectChanges()

在这种情况下,只执行了组件的构造函数,但没有执行生命周期钩子。

it('should create', () => {
  // initialization
  const fixture = TestBed.createComponent(DeclarationScrolltextComponent);
  const component = fixture.componentInstance;
  expect(component).toBeTruthy();

  // installing spies
  const spy = spyOn(component, 'serializeContentfulRichText');
  
  // executing render
  fixture.detectChanges();

  // assertions
  expect(spy).toHaveBeenCalledTimes(1);
});

推荐阅读