2016-06-14 88 views
7

我有一個Angular2,帶有非常基本的Jasmine測試的TypeScript應用程序設置。我想測試一個管道。用Jasmine測試Angular2/TypeScript管道

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

使用在HTML模板:

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

lpad.pipe.spec.ts - 我的測試(不工作)

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: TypeError: Cannot read property 'length' of undefined(…) 

我認爲問題出在我測試的「價值」和「參數」上。任何想法如何解決?

回答

8

這是因爲你的錯誤使用describe方法時:

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

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

您應該使用,而不是執行以下操作:

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

}); // <---------------- 
+3

你是100%正確的。謝謝。我還有另一個錯字「ToEqual('0001')」應該是「toEqual('0001')」。它正在工作。 –

+0

+1這幫助我進行測試,並指出On Angular v4 +管道可以單獨接收參數,如pipe.transform(value,arg1,arg2,arg3 ....) –