【问题标题】:Angular - Writing unit test case for switchMapAngular - 为 switchMap 编写单元测试用例
【发布时间】:2021-11-29 13:03:31
【问题描述】:

以下是我的两种服务方式

    getCountries(offset: number) {
          let url = this.configManagerService.countriesApiUrl;
          const httpHeaders = this.getHeaders();
          return this.httpClient.get(url + offset, { headers: httpHeaders });
        }
        
    getAllCountries(offset: number = 0, resultOld: any[] = []) {
      return this.getCountries(offset).pipe(
      
        //not getting covered
        switchMap((result: any) => {
          offset = result.length > 0 ? offset + result.length : -1;
          return offset >= 0
            ? this.getAllCountries(offset, [...resultOld, ...result])
            : of(resultOld);
        //not getting covered
        
        })
      );
    }

我能够编写涵盖getCountries 函数的单元测试用例,但无法理解如何涵盖我在cmets 之间提到的关于switchMap 的代码。试图用谷歌搜索,但找不到任何符合我要求的东西。这里的任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    这里是一个案例的例子。

    it('returns resultOld if result length is zero', (done: DoneFn) => {
      const resultOld = [];
      spyOn(service, 'getCountries').and.returnValue(of(resultOld));
      service.getAllCountries(2, resultOld).subscribe(results => {
        expect(results.length).toBe(0);
        done();
      });
    });
    
    it('calls getAllCountries over and over until converge', (done: DoneFn) => {
      const resultOld = [{ name: 'USA' }];
      spyOn(service, 'getCountries').and.returnValue(of(resultOld));
      service.getAllCountries(-1, resultOld).subscribe(results => {
        expect(results.length).toBe(1);
        done();
      });
    });
    

    【讨论】:

    • 嗨,阿里,我试过这个,但得到“警告:范围错误:超出最大调用堆栈大小”错误。我不确定这个错误是关于什么的。
    • 嘿Vamsi,对不起,我读错了。似乎您有一个堆栈溢出,其中getAllCountries 一遍又一遍地调用自己。我更改了测试以返回一个空数组。我还为您的第二种情况添加了一个测试。我很难推理,因为我不知道偏移量是什么,但我希望这个评论对你有所帮助。
    • 你好阿里,我仍然遇到同样的错误。我们可以在第一次迭代后打破循环吗?
    • 我刚刚删除了第二个测试用例,它导致了错误。第一个工作得很好。谢谢阿里。
    猜你喜欢
    • 2020-06-30
    • 1970-01-01
    • 2018-04-04
    • 2019-05-01
    • 1970-01-01
    • 2021-03-03
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多