簡體   English   中英

Angular 單元測試 observable 已返回

[英]Angular unit test observable was returned

如何編寫測試以確保調用了可觀察對象?

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

這些都不起作用。 非常感激任何的幫助。

假設它是可觀察的而不是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');

兩者都不起作用。

希望這對其他人有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM