Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Angular2 / TypeScript pipe with Jasmine

I have an Angular2 with TypeScript application setup with very basic Jasmine tests. I want to test one of my pipes.

lpad.pipe.ts

import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
    name: 'lpad'
})
export class LPadPipe implements PipeTransform {
    transform(value: any, args: string[]): any {
       let pad = args[0];
       return (pad + value).slice(-pad.length);
    }
}

usage in html template:

{{size.SizeCode | lpad:['0000']}}

lpad.pipe.spec.ts - My test (which doesn't work)

import { LPadPipe } from './lpad.pipe';

describe('LPadPipe'), () => {
    let pipe: LPadPipe;

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

    it('transforms "1" to "0001"', () => {
        let value: any = "1";
        let args: string[] = ['0000'];

        expect(pipe.transform(value, args)).ToEqual('0001')
    });

}

Error message:

Error: TypeError: Cannot read property 'length' of undefined(…)

I think the problem is with the "value" and "args" of my test. Any idea how to resolve?

like image 530
I_LIKE_FOO Avatar asked Jun 14 '16 11:06

I_LIKE_FOO


Video Answer


1 Answers

It's because you have errors when using the describe method:

describe('LPadPipe'), () => { // <----------------
  let pipe: LPadPipe;

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

  it('transforms "1" to "0001"', () => {
    let value: any = "1";
    let args: string[] = ['0000'];

    expect(pipe.transform(value, args)).ToEqual('0001')
  });

} // <----------------

You should use the following instead:

describe('LPadPipe', () => { // <----------------
  let pipe: LPadPipe;

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

  it('transforms "1" to "0001"', () => {
    let value: any = "1";
    let args: string[] = ['0000'];

    expect(pipe.transform(value, args)).ToEqual('0001')
  });

}); // <----------------
like image 165
Thierry Templier Avatar answered Sep 27 '22 23:09

Thierry Templier