2016-12-13 11 views
0

私はリストを取得するために必要なので、トークンを取得しようとしています。テストでAngular2トークンをモックしようとしています

describe('ListComponent Tests',() => { 
    let token: Angular2TokenService; 

    beforeAll(() => { 
    token.init(); 
    token.signIn('[email protected]', 'foobar'); 
    } 
} 

しかし、私はエラーになっています:今、私は

TypeError: Cannot read property 'init' of undefined 

を私がブロック記述追加し

import { Angular2TokenService } from 'angular2-token'; 

:私はangular2トークンをインポートしての開始します実際にテストでログイントークンを取得する方法が不明です。

答えて

0

tokenを初期化していないため、エラーになります。テスト中のコンポーネント用のモックを作成するときは、呼び出される予定の関数に対してspyを作成するだけで十分な場合があります。テストでは、コンポーネントが実際に関数を呼び出すことを確認したいだけです。模擬サービスのために実際のサービスを代用する必要もありますので、模倣を代用代理人として設定する必要があります。例

@Component({ 
    ... 
}) 
class TestComponent { 
    constructor(private token: Angular2TokenService) {} 

    ngOnInit() { 
    token.init(); 
    } 

    onLogin(email, password) { 
    token.signIn(email, password); 
    } 
} 

describe('..',() => { 
    let tokenStub; 
    let component; 
    let fixture; 

    beforeEach(() => { 
    tokenStub = { 
     init: jasmine.createSpy('init'), 
     signIn: jasmine.createSpy('signIn') 
    } 

    TestBed.configureTestingModule({ 
     declarations: [ TestComponent ], 
     providers: [{ provide: Angular2TokenService, useValue: tokenStub }] 
    }) 

    fixture = TestBed.createComponent(TestComponent); 
    component = fixture.componentInstance; 
    }) 

    it('should init the token when component created',() => { 
    fixture.detectChanges(); 
    expect(tokenStub.init).toHaveBeenCalled(); 
    }) 

    it('should signin token when component login',() => { 
    component.onLogin(); 
    expect(tokenStub.signIn).toHaveBeenCalledWith('[email protected]', 'foobar') 
    }) 
}) 

のためにあなたは関数が引数を取ることができtoHaveBeenCalledXxxメソッドを使用して呼ばれていることを確認することがわかります。

あなたがTestBed設定を使用していない場合は、簡単に、単純に

let tokenStub: Angular2TokenService; 
let component; 

beforeEach(() => { 
    tokenStub = { 
    init: jasmine.createSpy('init'), 
    signIn: jasmine.createSpy('signIn') 
    } as Angular2TokenService; 

    component = new TestComponent(tokenStub); 
}) 

it('..',() => { 
    component.ngOnInit(); 
    expect(tokenStub.init).toHaveBeenCalled(); 
}) 

上記にリンクされているスパイのドキュメントを読んで確認してくださいのような何かを行うことによって、それ孤立テストすることができます。特定のものを返すようなスパイで他のものを行うことができます。

関連する問題