【问题标题】:Angular unit test observable was returnedAngular 单元测试 observable 被返回
【发布时间】:2020-07-22 13:32:12
【问题描述】:

如何编写测试以确保调用了可观察对象?

示例:obj: any = {func: () => this.obs$}

我想编写一个测试来确保 obj.func 返回 this.obs$。

我尝试了以下方法:

it('should demonstrate obs is returned', () => {
    const spy = spyOn<any>(component, 'obs$').and.returnValue(of('test'));

    const ret = component.obj.func();

      expect(spy).toHaveBeenCalled();

// 2nd attempt

expect(ret).toEqual('test');
 })

这些都不起作用。任何帮助将不胜感激。

【问题讨论】:

    标签: angular unit-testing jasmine observable karma-runner


    【解决方案1】:

    你不能 spyOn obs$ 假设它是一个可观察的而不是一个函数。你只能监视函数。

    试试:

    it('should demonstrate obs is returned', (done) => { // add done callback here
      component.obs$ = of('test'); // assign obs$ to observable of 'test'
      const ret = component.obj.func();
      ret.subscribe(value => { // subscribe to the observable that previous function gives.
        expect(value).toBe('test');
        done(); // call done to tell Jasmine that you are done with the tests
      });
    });
    

    【讨论】:

    • 感谢您的帮助,请看我的回答进行小修正
    【解决方案2】:

    想在单独的答案中回复,虽然 AliF50 的答案有效,并且感谢您的帮助,但他们对间谍的看法不正确。它也与间谍一起工作,意思是:

    it('should demonstrate obs is returned', (done) => { // add done callback here
      spyOn<any>(component, 'obs$').and.returnValue(of('test'));
      const ret = component.obj.func();
      ret.subscribe(value => { 
        expect(value).toEqual('test');
        done();
      });
    });
    

    同样有效。

    但是,我找到了另一个同样有效的解决方案,而且更短:

    it('should demonstrate obs is returned', () => {
        expect(component.obj.func()).toEqual(component.obs$);
     })
    

    我的错误是尝试这样做:

    component.obs$ = of('test'); 
    
    expect(component.obj.func()).toEqual(of(test));
    
    //or
    
    expect(component.obj.func()).toEqual('test');
    

    两者都不起作用。

    希望这对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      相关资源
      最近更新 更多