Search code examples
angularkarma-jasmineangular-pipeangular-unit-test

Unit testing component throwing transform is not a function for a pipe


in my component class i have following get method:

get getCSVForDownload() {
    return defer(() => {
        this.downloadingData = true;
        return this.csvRepoService.getCSV(this.csvId).pipe(
            map((items: ICSV[]) => {
                let filteredItems = items;
                filteredItems = this.filterDateRangePipe.transform(filteredItems, this.timeFilterRange, 'createdDate');
                return filteredItems;
            }),
         );
    });

in the spec file of that component first I have created a mock pipe like this:

@Pipe({ name: 'filter' })
class MockPipe implements PipeTransform {
 public transform(items: any[], timeFilterRange: TimeFilterRange, fieldName: string): any   {
     return items;
  }
}

And in the beforeEach i have provided the pipe in following way:

 beforeEach(async () => {

    await TestBed.configureTestingModule({
        declarations: [ABCComponent],
        imports: [
            HttpClientTestingModule,
        ],
        providers: [
            { provide: FilterDateRangePipe, useValue: MockPipe },
            { provide: SecurityService, useValue: mockSecurityService }
        ],
        schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
    mockCsvRepoService = TestBed.inject(CsvRepoService );
    spyOn(mockCsvRepoService, 'getCSV').and.returnValue(of(testCSVs));
});

And the test I have written is following:

it('Should call getCSV when downloadCSV triggered', fakeAsync(() => {
    component.getCSVForDownload.subscribe()
    expect(mockCsvRepoService.getCSV).toHaveBeenCalled()
    flush();
  }));

Though I have provided mock object for FilterDateRangePipe which has transform method in it, I am still getting error like following

 TypeError: this.filterDateRangePipe.transform is not a function

What I am missing?


Solution

  • For mocking a pipe you should provide the MockedPipe via useClass instead of useValue.

    { provide: FilterDateRangePipe, useClass: MockPipe },