首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试RxJS主题:在测试中没有调用订阅方法

测试RxJS主题:在测试中没有调用订阅方法
EN

Stack Overflow用户
提问于 2019-11-01 19:42:58
回答 1查看 912关注 0票数 0

我有一个私人的attributeNameSubject. Subject有一个setAttributeName方法将字符串值传递给主题。我们使用getAttributeName.获得对该主题的参考我试着测试上面的代码,但我总是得到false-positive,,即测试通过,但我得到的测试没有预期的警告。结果,它根本没有调用订阅方法。

我正在测试这段代码的角度7。

代码语言:javascript
复制
private readonly attributeNameSubject = new Subject<string>();

get getAttributeName(): Subject<string> {
  return this.attributeNameSubject;
}

setAttributeName(value: any) {
  this.getAttributeName.next(value.attributeName);
}

it('should set attribute name on valid input', () => {
  service = TestBed.get(AttributeService);

  service.setAttributeName('some random string');
  service.getAttributeName.subscribe((data: string) => {
    expect(data).toEqual('some random string');
  });
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-01 20:02:59

您的代码有两个问题。

  1. setAttributeName向订阅者发出值,而getAttributeName则听可观察的值。因此,当您调用setAttributeName时,getAttributeName会发出一个值,但是没有任何订阅。因此,您应该首先订阅getAttributeName,然后调用setAttributeName来发出值。

  1. ,期望现在将被执行,但是测试将失败,因为数据被错误地传递了。getAttributeName在传递字符串时发出value.attributeName。您需要传递一个对象。

这是工作测试用例。

代码语言:javascript
复制
it('should set attribute name on valid input', () => {
    service = TestBed.get(AttributeService);

    service.getAttributeName.subscribe((data: string) => {
        expect(data).toEqual('some random string');
    });
    service.setAttributeName({ attributeName: 'some random string' });
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58665016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档