Search code examples
angularunit-testingjasminekarma-jasmineangular2-pipe

Angular 4 pipe unit test not working for basic pipe


Angular 4 pipe unit test not working for basic pipe

Karma error I get: TypeError: Cannot read property '0' of undefined

This is my pipe (very basic):

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "userPipe",
  pure: true
})

export class MyFilter implements PipeTransform {
   transform(items: any, [listOfItems]: any) {

     // Example of a pipe: listOfItems = listOfItems.filter(item => item.type === "test");

     return listOfItems;
  }
}

This is my pipe unit test:

import { MyFilter } from "./user.pipe";

describe("userPipe", () => {
  let pipe: MyFilter;
  let fakeResponse = ["abc"];

  beforeEach(() => {
    pipe = new MyFilter();
  });

  it("transforms abc to abc", () => {
    expect(pipe.transform(fakeResponse)).toEqual(fakeResponse);
  });
});

Solution

  • Update your transform function first, test will work with this code

    export class MyFilter implements PipeTransform {
       transform( items: Array<any> ) {
         return listOfItems;
      }
    }