【问题标题】:Jasmine unit testing - mat-Autocomplete filter classJasmine 单元测试 - mat-Autocomplete 过滤器类
【发布时间】:2021-11-24 14:11:47
【问题描述】:

我正在为一个 Angular 应用程序编写 jasmine 单元测试,覆盖率非常好,但很难找到一种测试可观察过滤器类的好方法,用于 mat-autocomplete 数据填充。

ts 类:

  dataFilter(val: string): Observable<any[]> {
    return this.getAPI.get()
      .pipe(
        map(response => response.filter(option => {
          return option.foo.toLowerCase().includes(val.toLowerCase());
        }))
      );
   }

到目前为止对这个类的单元测试:

  it('should test filtered data for autocomplete', () => {
    getApiSpy.get.and.returnValue(of(DATA));
    component.dataFilter("");
    expect(getApiSpy.get).toHaveBeenCalled();
  });

这涵盖了第一次返回(return this.getAPI.get()),但不包括从 .pipe 向下的所有内容。以前有没有人测试过这些类型的课程并有任何提示,正确的方法是什么?

谢谢, 奥利

【问题讨论】:

  • 你的 component.dataFilter(""); call 在这里听起来很可疑 - 你得到了一个冷的可观察的,有意想不到的结果。 component.dataFilter("").subscribe(() => { // tests here}) 会是更好的选择。对返回 observables 的函数使用 $ 后缀将有助于使这些问题更加明显。

标签: angular unit-testing angular-material jasmine observable


【解决方案1】:
it('should filter', () => {

    const getApiMock = [
        { foo:'abc'},
        { foo:'def'},
        { foo:'xyz'},
    ];

    // spy on getAPI.get() and return getApiMock here...

    const expected = [
        { foo:'xyz'},
    ];

    component.dataFilter('Y').subscribe(actual => {
        expect(actual).toEqual(expected);
    });
});

【讨论】:

  • 谢谢,这成功了!可怕的粉红色线从我的代码覆盖率报告中消失了。
  • @YorkshireDevOliver 太棒了!请考虑将回复标记为已接受。
猜你喜欢
  • 2020-03-21
  • 2020-08-12
  • 1970-01-01
  • 2018-10-30
  • 2017-06-26
  • 1970-01-01
  • 2018-07-01
  • 2017-04-04
  • 2013-08-29
相关资源
最近更新 更多