私のコンポーネントには、注文の依存関係のメソッドを購読するさまざまなメソッドがあり、それは観測値を返します。
私はこれらの観察者がreturn/errorの場合、私の方法で正しいことをするように、Jestユニットテストを書きたいと思います。
次の例では、doAThing
が発射されたかどうかを確認するテストを書き込もうとしています。以下のテストのどちらも機能しません。どちらもエラーで失敗します
'returnMyObServable.subscribeは関数ではありません'です。
// Example method to test component
public testFunction (): void {
this.myService.returnMyObservable.subscribe(
( value ) => this.doAThing( value )
)
}
_
describe( 'myComponemt', () => {
let fixture;
let myServiceMock;
beforeEach( () => {
myServiceMock = {
returnMyObservable: fn()
}
fixture = new myComponent( myServiceMock );
});
// 1) I have tried mocking with a returned value
it ( 'should call do a thing when value is returned', () => {
myServiceMock.returnMyOnservable.mockReturnValue( true );
fixture.testFunction();
expect( fixture.doAThing ).toHaveBeenCalled();
});
// 2) I have tried returning an observable
it ( 'should call do a thing when value is returned', () => {
myServiceMock.returnMyOnservable.mockReturnValue( of( true ) );
fixture.testFunction();
expect( fixture.doAThing ).toHaveBeenCalled();
});
});
_
これが解決策です:
index.ts
:
export class MyComponent {
private myService;
constructor(myService) {
this.myService = myService;
}
public testFunction(): void {
this.myService.returnMyObservable.subscribe(value => this.doAThing(value));
}
public doAThing(value) {}
}
_
index.spec.ts
:
import { MyComponent } from './';
describe('MyComponent', () => {
let fixture;
let myServiceMock;
beforeEach(() => {
myServiceMock = {
returnMyObservable: {
subscribe: jest.fn()
}
};
fixture = new MyComponent(myServiceMock);
});
it('should call do a thing when value is returned', () => {
let observer;
myServiceMock.returnMyObservable.subscribe.mockImplementation(handler => {
observer = handler;
});
jest.spyOn(fixture, 'doAThing');
fixture.testFunction();
observer();
expect(fixture.doAThing).toHaveBeenCalled();
});
});
_
100%のカバレッジの単体テスト結果:
PASS src/stackoverflow/58815471/index.spec.ts (7.367s)
MyComponent
✓ should call do a thing when value is returned (5ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 8.773s
_
ソースコード: https://github.com/mrdulin/jest-codelab/tree/master/src/stakeverflow/58815471