如何在 angular 测试中检查从管道返回的数组的长度?

How to check the length of a returned array from a pipe in an angular test?

我有一个管道可以过滤给定数组的关键字和 return 任何匹配项。在此示例中,关键字 'Music' 应该 return 3 个结果。我如何检查我的测试以查看它是否 returns 3 结果?是否可以只使用包含关键字 'Music' 的元素制作 dummyData[] 的副本?

test.spec.ts

describe('ArrayFilterPipe', () => {

    let pipe: ArrayFilterPipe;

    const dummyData = [
      {id: 1, name: 'Rap Music'},
      {id: 2, name: 'Hip Hop'},
      {id: 3, name: 'Country Music'},
      {id: 4, name: 'Radio Stations'},
    ];

    it('the keyword "Music" should return 3 results', () => {
        expect(pipe.transform(dummyData, 'Music')).toEqual(); // Is it possible to check the length or do I have to create a copy of dummyData with only the elements that contain 'Music'?
    });

 }

ArrayFilterPipe

export class ArrayFilterPipe implements PipeTransform {

  transform(data[], keyword: string) {
    keyword = keyword.toLowerCase();
    return data.filter(x => {
      return x.name.toLowerCase().includes(keyword);
    });
  }
}

您没有在任何地方创建实例或 ArrayFilterPipe。创建 ArrayFilterPipe 的实例后,您可以像下面这样检查长度

describe('ArrayFilterPipe', () => {
    const pipe = new ArrayFilterPipe();

    const dummyData = [
        { id: 1, name: 'Rap Music' },
        { id: 2, name: 'Hip Hop' },
        { id: 3, name: 'Country Music' },
        { id: 4, name: 'Radio Stations' },
    ];

    it('the keyword "Music" should return 2 results', () => {
        expect(pipe.transform(dummyData, 'Music').length).toEqual(2);
    });
});

此外,根据您提供的 dummyData,它应该 return 2 个结果而不是 3 个。