簡體   English   中英

Angular Jest 中的 Testing.pipe

[英]Testing .pipe in Angular Jest

我想測試以下.ts 文件:

create(entityResourceID, params: any): Observable <any>{
  const url = `${this.apiUrl}/${entityResourceID}/assignee`;
  return this.http.post(url, params).pipe(
    map(() => { this.toaster.success('Successfully Asssigned Email'); }),
    catchError((error) => [
      console.error(error),
      this.toaster.error('Failed Assigning Email')
    ])
  );
}

但是我目前收到錯誤.pipe is not a function

這是我當前的測試 spec.ts 文件:

describe('create', () => {
    it('should return a valid url', () => {
        const spy = jest.spyOn(mockHttpClient, 'post').mockReturnValue('test');
        const result = component.create(testEntityID, {});
        expect(spy).toBeCalledWith('entities/url/assignee', {});
        expect(result).toStrictEqual('test');
    });
});

我知道這很困難,因為我要返回一個 Observable 類型。 我需要從我的間諜返回一個 Observable,這樣我就可以測試我的兩個案例,但我該怎么做呢?

此錯誤是因為您模擬了post方法並返回了一個字符串值,而不是一個包含您的值的 Observable。 我不知道你是否使用 rxjs,但你可以這樣做..

import { of } from 'rxjs';

const spy = jest.spyOn(mockHttpClient,'post').mockReturnValue(of('test'));

of方法是Obeservable.of(yourValueHere)的簡寫方式

暫無
暫無

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

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