Testing pipes

A pipe is basically a class that implements the PipeTransform interface, thus exposing a transform() method that is usually synchronous. Pipes are therefore very easy to test. We will begin by testing a simple pipe, creating, as we mentioned, a test spec right next to its code unit file. The code is as follows:

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

@Pipe({
name: 'formattedpipe'
})
export class FormattedPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
return "banana" + value;
}
}

Our code is very simple; we take a value and add banana to it. Writing a test for it is equally simple. The only thing we need to do is to import the pipe and verify two things:

  • That it has a transform method
  • That it produces the expected results

The following code writes a test for each of the bullet points listed earlier:

import FormattedTimePipe from './formatted-time.pipe';
import { TestBed } from '@angular/core/testing';

describe('A formatted time pipe' , () => {
let fixture;

beforeEach(() => {
fixture = new FormattedTimePipe();
})

// Specs with assertions
it('should expose a transform() method', () => {
expect(typeof formattedTimePipe.transform).toEqual('function');
});

it('should produce expected result', () => {
expect(fixture.transform( 'val' )).toBe('bananaval');
})
});

In our beforeEach() method, we set up the fixture by instantiating the pipe class. In the first test, we ensure that the transform() method exists. This is followed by our second test that asserts that the transform() method produces the expected result.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset