javascript - 我如何用 Jest 来模拟异步提取?

标签 javascript node.js jestjs

几天来我一直在努力想办法正确地测试这段代码:(

const request = require('superagent');

const getDog = () => {
  return request.get('https://dog.ceo/api/breeds/image/random');
};

it('resolves', () => {
  // Expect mocked response
});

it('rejects', () => {
  // Expect mocked response
});

最佳答案

在大多数情况下,您的代码会从 API 中获取一些值,然后对其进行解析并使用它来制作一些东西。
因此,您不想进行真正的 API 调用而是模拟它。
有几种方法可以做到这一点。一种可能是模拟 superagent 库中的唯一方法。

// tell jest not to mock superagent because we'll mock the only method
jest.unmock('superagent');

const request = require('superagent');

const getDog = () => {
  return request.get('https://dog.ceo/api/breeds/image/random');
};

it('resolves', () => {
  // mock the get request to resolve object
  request.get = jest.fn().mockResolvedValue({
  message: 'Your message'
  });
  // Expect mocked response
  expect.assertions(1);
  return expect(getDog()).resolves.toEqual({
  message: 'Your message'
  });
});

it('rejects', () => {
  // mock the get request to reject object
  request.get = jest.fn().mockRejectedValue({
  message: 'Your error'
  });
  // Expect mocked response
  expect.assertions(1);
  return expect(getDog()).rejects.toEqual({
    message: 'Your error'
  });
});

我使用了expect.assertions(1),有一个reason :

This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.

有些链接可以帮助您: mockFn.mockResolvedValue(value) , .rejects

关于javascript - 我如何用 Jest 来模拟异步提取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50692010/

相关文章:

javascript - 为什么我不能用 javascript 同时更改图像的高度和宽度?

javascript - jQuery : How to wait scrollTop animation to finish before do something?

javascript - JS全局变量类型的区别

node.js - 是否可以让 Node.js 使用 Rhino 作为 Javascript 引擎?

javascript - AJAX、PHP、SQL newsfeed 每次都会出错

javascript - 将 JSON 查询条件转换为 MongoDB/Mongoose 操作

css - 如何模糊具有透明度的 Electron BrowserWindow

reactjs - React 和 Jest 测试 : nested component connected to Redux gives Invariant Violation error

javascript - 使用 Jest ("Cannot read property ' __extends' of null 进行单元测试 typescript 类”)

javascript - JavaScript React 项目中的高 Jest 堆内存使用率