typescript - 如何完全覆盖对 NestJs http 请求进行单元测试?

标签 typescript unit-testing jestjs nestjs

我无法测试我的 NestJs 服务。我写了一个方法,它执行 GET http 请求:

getEntries(): Observable<Entries[]> {
    Logger.log(`requesting GET: ${this.apiHost}${HREF.entries}`);
    return this.http.get(`${this.apiHost}${HREF.entries}`).pipe(
      catchError((error) => {
        return throwError(error);
      }),
      map(response => response.data)
    );
  }

我想为此方法编写单元测试。此单元测试应涵盖此方法的所有行。
我尝试使用“nock”包来模拟此 http 请求,但无论我如何尝试,覆盖结果始终相同。
return throwError(error);

map(response => response.data);

这两条线被发现了。

这是我的测试文件:
describe('getEntries method', () => {
    it('should do get request and return entries', () => {
      nock('http://localhost:3000')
        .get('/v1/entries')
        .reply(200, {
          data: require('../mocks/entries.json')
        });
      try {
        const result = service.getEntries();
        result.subscribe(res => {
          expect(res).toEqual(require('../mocks/entries.json'));
        });
      } catch (e) {
        expect(e).toBeUndefined();
      }
    });
    it('should return error if request failed', () => {
      nock('http://localhost:3000')
        .get('/v1/entries')
        .replyWithError('request failed');
      service.getEntries().subscribe(res => {
        expect(res).toBeUndefined();
      }, err => {
        expect(err).toBe('request failed');
      })
    });
  });

最佳答案

我没用过nock过去,但你可以告诉HttpService使用时应如何回应 jest.spyOn .要记住的最重要的事情是返回是“同步的”,因为它是一个可观察的返回。为了测试您的阳性案例,您可以执行以下操作

it('should do the request and get the entries', (done) => {
  const httpSpy = jest.spyOn(httpService, 'get')
    .mockReturnValue(of({data: require('../mocks/entries.json')}))
  let data = {};
  service.getEntires().subscribe({
    next: (val) => {data = val},
    error: (err) => { throw error; }
    complete: () => {
      expect(data).toEqual(require('../mocks/entries.json'))
      done();
    }
});

同样,对于错误路由,您可以使用 throwError()运算符(operator)。

两者 ofthrowError进口自 rxjs .唯一需要注意的是,使用此方法,您确实需要获取 HttpService从当前模块上下文,类似于您将如何获得任何其他服务。只是确保把它叫出来。

关于typescript - 如何完全覆盖对 NestJs http 请求进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61500218/

相关文章:

reactjs - 如何在 Typescript 中为 React useReducer Hook 操作创建类型定义?

c# - 除非删除 App.Config,否则不会发现 Visual Studio 2017 单元测试

objective-c - XCode 单元测试中没有这样的模块 <product module name>

unit-testing - 如何对懒惰进行单元测试

reactjs - 如何模拟另一个文件中的返回值?

html - 从 HostListener 访问 HTML 元素

typescript - 如何在使用 React Navigation 和 TypeScript 时使用 Jest 和 Enzyme 对静态 navigationOptions 进行单元测试?

javascript - joi_1.default.validate 不是函数

reactjs - 当我使用 react 测试库、react.lazy 和 suspense Jest 运行相同的测试两次时,为什么加载程序没有在第二次测试中显示?

node.js - 意外的 Node 类型错误 SequenceExpression with jest