开玩笑地模拟节点获取,创建用于模拟的响应对象

Mocking node-fetch with jest creating a Response Object for mocking

我正在尝试创建用于开玩笑的响应对象,我似乎无法获得正确的语法。

初始化,

jest.mock('node-fetch')
const fetch = require('node-fetch')
const { Response, Headers } = jest.requireActual('node-fetch')

// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class
const meta = {
  'Content-Type': 'application/json',
  'Accept': '*/*',
  'Breaking-Bad': '<3'
}
// You can in fact use any iterable objects, like a Map or even another Headers
const headers = new Headers(meta)
const copyOfHeaders = new Headers(headers)

const ResponseInit = {
  status: 200,
  statusText: 'fail',
  headers: headers
}

有基础测试

  test('Basic Test', async () => {
    const token = ''
    const getDocList = new Response(JSON.stringify(downloadDocumentData), ResponseInit)
    fetch.mockResolvedValueOnce(Promise.resolve(getDocList))
    await module.doSomething('mock', token)
      .then( async(res) => {
        await expect(res.data).toEqual(Object)
      })
  }, 5000)

我收到一个错误

     FetchError {
        message:
         'invalid json response body at  reason: Unexpected token H in JSON at position 2',
        type: 'invalid-json' }

如何初始化有效的响应 json,我尝试了很多不同的方法。

按照 https://jestjs.io/docs/en/bypassing-module-mocks 上的文章,但我想 return 并改为测试 json。

我们应该使用 jest.mock(moduleName, factory, options) 模拟 node-fetch 模块和 fetch 函数。

为了构造fetch函数的响应对象,需要使用node-fetch模块提供的Responseclass,所以使用jest.requireActual(moduleName) 以获得原始的、未模拟的 node-fetch 模块和 Response class.

当然我们可以任意构造response对象,但是Responseclass的实例确实很接近真实的response

headers对象也是如此。

这是一个工作演示:

index.js:

const fetch = require('node-fetch');

module.exports = {
  async doSomething(url, token) {
    return fetch(url).then(res => res.json());
  }
};

index.spec.js:

jest.mock('node-fetch');

const fetch = require('node-fetch');
const { Response, Headers } = jest.requireActual('node-fetch');
const mod = require('./');

const meta = {
  'Content-Type': 'application/json',
  Accept: '*/*',
  'Breaking-Bad': '<3'
};
const headers = new Headers(meta);
const copyOfHeaders = new Headers(headers);

const ResponseInit = {
  status: 200,
  statusText: 'fail',
  headers: headers
};

test('Basic Test', async () => {
  const token = '';
  const downloadDocumentData = { data: {} };
  const getDocList = new Response(JSON.stringify(downloadDocumentData), ResponseInit);
  fetch.mockResolvedValueOnce(Promise.resolve(getDocList));
  const res = await mod.doSomething('mock', token);
  expect(res).toEqual({ data: {} });
  expect(fetch).toBeCalledWith('mock');
});

单元测试结果:

 PASS  src/Whosebug/58648691/index.spec.js
  ✓ Basic Test (5ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.557s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/Whosebug/58648691