单元测试:为了观察值随时间的变化,返回观察值以返回主题的模拟服务会导致TS抛出TS2339 [英] Unit test: Mocking service that returns observables to return subjects in order to test change of values over time causes TS to throw TS2339

查看:74
本文介绍了单元测试:为了观察值随时间的变化,返回观察值以返回主题的模拟服务会导致TS抛出TS2339的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务,该服务返回ngrx选择器公开的值,还有一个定义此服务的组件,将其注入并根据该服务返回的值设置属性.

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.

我正在使用服务的模拟编写组件的单元测试,并且我需要模拟服务为每个单元测试返回不同的值. 为了做到这一点,我定义了模拟服务类,以便它返回主题而不是可观察对象.测试运行,但是TS抛出错误,表明模拟服务的接口与真实服务的接口不匹配,因为真实服务返回可观察的值.

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

stackblitz可以正常工作并且测试可以正确运行,但是正如您所看到的,TS会引发错误 TS2339:类型可观察"上不存在属性下一个"

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'

我发现我可以添加 //@ ts-ignore 在每次调用.next()以告知TypeScript编译器忽略该错误的上方,但这似乎不是最佳解决方案.

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?

推荐答案

您可以使用BehaviorSubject上的.asObservable()方法使真实服务和模拟返回相同的内容.您还可以使用do()方法,在BehaviorSubject中设置一个新值.

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); }
}  

我希望这会有所帮助.

这篇关于单元测试:为了观察值随时间的变化,返回观察值以返回主题的模拟服务会导致TS抛出TS2339的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆