angular - 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();
});
但是间谍没有被调用并且组件没有被创建(两个期望都失败了)。
解决方案
如果要存根测试组件的方法,则需要在 之后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);
});
推荐阅读
- flutter - 如何在飞镖中等待 Map.forEach()
- ansible - 稳定 | 将键附加到列表中的每个字典
- prometheus - 使用 Grafana 文本图的参考变量值
- javascript - 动画后CSS背景变暗
- python - 如何将 numpy.array 写入文件并保留所有数字?
- php - 将加号字符串转换为运算符
- python - 在特定字符正则表达式之间查找文本
- python - 带有 Pandas_datareader 的 RemoteDataError
- azure-data-factory - azure df 中的复制活动价格
- r - 从 r 中的逻辑回归创建栅格图层