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