testing - 模拟主题的返回值 - 使用 Jasmine 进行单元测试
问题描述
我是单元测试,部分测试有一个主题。我是主题的新手,并且了解它们如何工作的一般要点,但我正在努力模拟一个返回值。我尝试了各种方法,希望能找到正确的方法,比如使用 spy 和 returnvalue 来返回数字 3。
在组件中:
....
private searchEvent: Subject<string> = new Subject<string>();
....
this.searchEvent.pipe(debounceTime(500)).subscribe(value => {
if (value.length >= 3) {
this.retrieveAssets(value);
}
})
....
在我的规范文件中,我基本上有:
component['searchStockEvent'].subscribe(x=> of(3));
fixture.whenStable().then(() => {
expect(component['retrieveAssets']).toHaveBeenCalled();
});
解决方案
searchEvent
私有化将很难直接在主题上调用 next ,因此您必须找到一种方法使searchEvent
emit 值大于 3 并走这条路。
对于此演示,我们将其公开:
....
public searchEvent: Subject<string> = new Subject<string>();
....
this.searchEvent.pipe(debounceTime(500)).subscribe(value => {
if (value.length >= 3) {
this.retrieveAssets(value);
}
})
....
import { fakeAsync, tick } from '@angular/core/testing';
it('should call retrieve assets', fakeAsync(() => {
component.searchEvent.next(3);
// we need to pass 501ms in a fake way
tick(501);
expect(component.retreiveAssets).toHaveBeenCalled();
}));
推荐阅读
- gradle - Gradle 禁用 javadoc,部署时除外
- python - 我可以用什么来创建一个可以使用在线连接的程序(在 python 中)?
- wordpress - 在 wordpress 中创建和关注列表
- python - Pandas 到 JSON,多层次结构
- google-apps-script - 是否可以将 .gs 文件上传到复制的谷歌文档的应用程序脚本项目?
- c++ - 为什么这段代码被认为是优化的?
- bash - 将在流程脚本中生成的文件的内容保存到 Nextflow 变量中
- javascript - 通过 Google 表格解析时出现“JavaScript 运行时意外退出”错误
- python - 获取AttributeError:'ASGIRequest'对象在daphne django中没有属性'get'
- r - Dplyr Summarize:组合某些组的值