首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mocking node-fetch with jest创建用于mocking的响应对象

Mocking node-fetch with jest创建用于mocking的响应对象
EN

Stack Overflow用户
提问于 2019-11-01 01:40:49
回答 1查看 6K关注 0票数 6

我正在尝试创建响应对象,以便使用jest进行模仿,但我似乎无法获得正确的语法。

初始化,

代码语言:javascript
复制
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
}

通过基本的测试

代码语言:javascript
复制
  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)

我收到一个错误,即

代码语言:javascript
复制
     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上的文章,但我想返回并测试json。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-01 13:01:35

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

为了构造fetch函数的响应对象,您需要使用node-fetch模块提供的Response类,因此使用jest.requireActual(moduleName)获取原始的、未模拟的node-fetch模块和Response类。

当然,我们可以任意构造response对象,但是Response类的实例非常接近真实的响应。

headers对象也是如此。

下面是一个有效的演示:

index.js

代码语言:javascript
复制
const fetch = require('node-fetch');

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

index.spec.js

代码语言:javascript
复制
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');
});

单元测试结果:

代码语言:javascript
复制
 PASS  src/stackoverflow/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/stackoverflow/58648691

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58648691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档