Angular 已返回单元测试可观察对象

Angular unit test observable was returned

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

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

我想编写一个测试来确保 obj.func returns 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');
 })

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

你不能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
  });
});

想单独回答,虽然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');

两者都不行。

希望这对其他人有帮助。