Unit test: Mocking service that returns observables to return subjects in order to test change of values over time causes TS to throw TS2339

三世轮回 提交于 2019-12-23 19:44:59

问题


I have a service that returns the values exposed by ngrx selectors, and a component that defines this service, injects it and sets properties based on the values returned by the service.

I am writing unit tests for the component using a mock of the service, and I need the mock service to return different values for each unit test. In order to do this I have defined the mock service class so it returns subjects instead of observables. The tests run, but TS throws an error saying that the interface of the mock service does not match the interface of the real service, as the real service returns observables.

Stackblitz

The stackblitz works and the tests run correctly, but as you can see TS throws the error TS2339: Property 'next' does not exist on type 'Observable'

I have found I can add // @ts-ignore above each call to .next() to tell the TypeScript compiler to ignore the error, but this doesn't seem to be the best solution.

Maybe there is a better way of mocking the service altogether so it still returns observables but I can return a different value for each unit test?


回答1:


You can have the real service AND the mock return the same thing, using the .asObservable() method on the BehaviorSubject. You could also use the do() method you have to set a new value into the BehaviorSubject.

To demonstrate, I put together this StackBlitz. Here is the MockTestService from that StackBlitz:

MockTestService {
    private _test$ = new BehaviorSubject(10);
    public test$ = this._test$.asObservable();
    do(param: number): void { this._test$.next(param); }
}  

I hope this helps.



来源:https://stackoverflow.com/questions/54191645/unit-test-mocking-service-that-returns-observables-to-return-subjects-in-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!