【问题标题】:Testing a RxJS Subject: subscribe method not getting called in the test测试 RxJS 主题:在测试中未调用订阅方法
【发布时间】:2019-11-01 19:42:58
【问题描述】:

我有一个私人 Subject attributeNameSubject。有一个 setAttributeName 方法将字符串值传递给主题。我们使用 getAttributeName 获得对该主题的引用。我正在尝试测试上面的代码,但我总是得到 false-positive,即测试通过但我得到 test has no expect 警告。原来它根本没有调用 subscribe 方法。

我正在 Angular 7 中测试此代码。

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

【问题讨论】:

    标签: angular unit-testing jasmine observable angular-test


    【解决方案1】:

    您的代码有两个问题。

    1. setAttributeName 将值发送给订阅者,而 getAttributeName 监听 observable。因此,当您调用 setAttributeName 时,getAttributeName 会发出一个值,但没有订阅它。所以你应该先订阅getAttributeName,然后调用setAttributeName发出值。
    2. 现在将执行期望,但测试将失败,因为数据传递不正确。 getAttributeName 在您传递字符串时发出 value.attributeName。您需要传递一个对象。

    这是有效的测试用例。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-27
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2020-06-22
      • 2021-08-13
      相关资源
      最近更新 更多