简体   繁体   中英

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?

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')
  });

}); // <----------------

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM