Mr.M
Mr.M

Reputation: 1480

How to unit test for the given code in Angular 8

I am trying to execute unit testing for the below code

  applyFilter(filterValue: string) {
   this.dataSource.filter = filterValue.trim().toLowerCase();
   this.DMDataSource.filter = filterValue.trim().toLowerCase();
   // console.log(this.dataSource.filter);
 }

Here is my Spec code for that

  it('apply filter', () => {
    spyOn(component, 'applyFilter');
    component.applyFilter('filterValue');
    expect(component.applyFilter);
  })

Still in the browser showing that code is highlighted in red, meaning it was not covered. What am I doing wrong here?

Upvotes: 0

Views: 1060

Answers (1)

IAfanasov
IAfanasov

Reputation: 4993

To test a method you need to check the results of its execution. By spying on it you prevent its execution. The better approach would be to execute the method and check the results. It is also a good practice to have only one expectation inside one it block. Makes test more easy to maintain.

describe('applyFilter' ()=> {

   it('should set the dataSource filter to the provided argument' ()=> {
      component.applyFilter('filterValue');

      expect(this.dataSource.filter).toEqual('filterValue');
   })

   it('should set the dataSource filter to the provided argument' ()=> {
      component.applyFilter('filterValue');

      expect(this.DMDataSource.filter).toEqual('filterValue');
   })

  // test for trimming and lower case to here
})

Upvotes: 1

Related Questions