首页 > 解决方案 > 模拟主题的返回值 - 使用 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();
        });

标签: testingmockingjasminesubject

解决方案


searchEvent私有化将很难直接在主题上调用 next ,因此您必须找到一种方法使searchEventemit 值大于 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();
}));

推荐阅读