【问题标题】:Mocking a return value for a Subject - Unit Testing with Jasmine模拟主题的返回值 - 使用 Jasmine 进行单元测试
【发布时间】:2021-08-06 13:32:39
【问题描述】:

我正在进行单元测试,部分测试有一个主题。我是 Subjects 的新手,并且了解它们如何工作的一般要点,但我正在努力模拟一个返回值。我尝试了各种方法,希望能找到正确的方法,比如使用 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();
        });

【问题讨论】:

    标签: testing mocking jasmine subject


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-09
      • 2015-09-18
      • 1970-01-01
      • 2021-02-16
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多