A pipe is basically a class that implements the PipeTransform
interface, hence exposing a transform()
method that is usually synchronous. In that sense, pipes are the perfect candidates for taking our first steps in the world of unit testing Angular 2 modules. We will begin then by testing FormattedTimePipe
, creating as we mentioned a test spec right next to its code unit file. The code is as follows:
app/shared/pipes/formatted-time.pipe.spec.ts
import FormattedTimePipe from './formatted-time.pipe'; import { describe, expect, it, beforeEach} from '@angular/core/testing'; describe('shared:FormattedTimePipe', () => { let formattedTimePipe: FormattedTimePipe; beforeEach(() => formattedTimePipe = new FormattedTimePipe()); // Specs with assertions it('should expose a transform() method', () => { expect(typeof formattedTimePipe.transform).toEqual('function'); }); it('should transform 50 into "0h:50m"', () => { expect(formattedTimePipe.transform(50)).toEqual('0h:50m'); }); it('should transform 75 into "1h:15m"', () => { expect(formattedTimePipe.transform(75)).toEqual('1h:15m'); }); it('should transform 100 into "1h:40m"', () => { expect(formattedTimePipe.transform(100)).toEqual('1h:40m'); }); });
We import the pipe token in order to instantiate it and bind it to a variable before running each test, which will grab this variable and introspect its type or will pass different values to its transform method to check whether we obtain the expected value or not.
What about the testing cycle we mentioned earlier? In a normal scenario, we would add our test first, leveraging the test itself to design our pipe interface. Our test would fail at first and then we would develop its implementation. When defining our assertions, we should run the extra mile and define assertions where our pipe has to confront wrong inputs or unexpected scenarios. As our code evolves and is refactored, our tests will have to be refactored and simplified as well.
Save the file and declare it in our specCollection
array at our spec runner (you can safely remove the reference to the test spec since we will no longer use it):
spec-runner.html
...
var specCollection = [
'test/setup',
'app/shared/pipes/formatted-time.pipe.spec'
];
...
In the next sections, we will see how to create different tests.
Every time we create a new test spec, you will have to append its path (without the file extension) to the specCollection
array variable at spec-runner.html
. Do not forget this, since we will not make explicit reference to this requirement from now on. Failing to include the reference will turn into non-execution of the test. Therefore, the spec will not show up in the spec runner report.