本文介绍了如何通过 Jest 在 Node.js 中模拟 fetch 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过 Jest 在 Node.js 中模拟 fetch 函数?

How can I mock fetch function in Node.js by Jest?

api.js

'use strict'
var fetch = require('node-fetch');

const makeRequest = async () => {
    const res = await fetch("http://httpbin.org/get");
    const resJson = await res.json();
    return resJson;
};

module.exports = makeRequest;

test.js

describe('fetch-mock test', () => {
    it('check fetch mock test', async () => {

        var makeRequest = require('../mock/makeRequest');

        // I want to mock here


         global.fetch = jest.fn().mockImplementationOnce(() => {
           return new Promise((resolve, reject) => {
            resolve({
                ok: true,
                status,
                json: () => {
                    return returnBody ? returnBody : {};
                },
               });
          });
        });

        makeRequest().then(function (data) {
            console.log('got data', data);
        }).catch((e) => {
            console.log(e.message)
        });

    });
});

我尝试使用 jest-fetch-mock、nock 和 jest.模拟但失败.

I tried to use jest-fetch-mock, nock and jest.mock but failed.

谢谢.

推荐答案

您可以使用 jest.mock 模拟 node-fetch.然后在您的测试中设置实际的模拟响应

You can mock node-fetch using jest.mock. Then in your test set the actual mock response

import fetch from 'node-fetch'
jest.mock('node-fetch', ()=>jest.fn())

describe('fetch-mock test', () => {
    it('check fetch mock test', async () => {

        var makeRequest = require('../mock/makeRequest');


         const response = Promise.resolve({
                ok: true,
                status,
                json: () => {
                    return returnBody ? returnBody : {};
                },
               })
        fetch.mockImplementation(()=> response)
        await response
        makeRequest().then(function (data) {
            console.log('got data', data);
        }).catch((e) => {
            console.log(e.message)
        });

    });
});

这篇关于如何通过 Jest 在 Node.js 中模拟 fetch 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:37