简体   繁体   English

Angular 单元测试过滤谓词 function 和 Jasmine

[英]Angular unit testing Filter Predicate function with Jasmine

I have a filter predicate function which I use to filter a mat-table in angular我有一个过滤谓词 function 用于过滤 angular 中的垫表

this.dataSource.filterPredicate = this.myService.tableFilter();

tableFilter(): (data: any, filter: string) => boolean {
    let filterFunction = function (data, filter): boolean {
      let filterValues = JSON.parse(filter);
      ... my logic ...
    };
    return filterFunction;
  }
}

I want to write a unit test to test this filter predicate function我想写一个单元测试来测试这个过滤谓词 function

it('filter table', inject(
    [MyService],
    (service: MyService) => {

      // how to do this?
      let messageObject = service.tableFilter(dummyData, 
        getDummyFilterValues());
    }
  ));

How do I call the service.tableFilter function in the unit test?如何在单元测试中调用service.tableFilter function?

Replace the logic where I am returning an object in the below code with a boolean return in your case.在您的情况下,用 boolean 返回替换我在下面的代码中返回 object 的逻辑。 I think the question is regarding how to call the returned function我认为问题是关于如何调用返回的 function

typescript code typescript代码

tableFilter(): (data: any, filter: string) => any {
    const filterFunction = (data, filter) => {
      const filterValues = JSON.parse(filter);
      return data.find(d => {
        return d.num === filterValues.num;
      });
    };
    return filterFunction;
  }

spec file/ unit test block规范文件/单元测试块

  it('test filterfx', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    const filterfx =  app.tableFilter();
    expect(filterfx(app.data,  JSON.stringify({ num: 'one' })).num).toEqual('one');
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM