我知道如何从依赖项中模拟一个函数,但现在我有一个不在依赖项中的函数,它在我想要测试的实际组件中。我怎么能告诉茉莉花简单地忽略它?
当我运行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();
});
但是间谍没有被调用并且组件没有被创建(两个期望都失败了)。
