I have various methods in my components that subscribe to methods in injected dependencies, that return observables.
I want to write Jest unit tests to ensure that when these observables return / error, my methods do the correct thing.
In the below example I am trying to write a test that checks if doAThing
has fired. Neither of the below tests work. They both fail with errors like
'returnMyObservable.subscribe is not a function'.
// 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();
});
});
of(value)
. I just called the component that executes the subscription inside of it, tested thedoAThing
function withtoHaveBeenCalled()
and addeddone()
at the end of the test case. All my tests seem to pass with this setup. – Gaseous