小编You*_*ada的帖子

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

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

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;
Run Code Online (Sandbox Code Playgroud)

测试.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: () => { …
Run Code Online (Sandbox Code Playgroud)

node.js jestjs

9
推荐指数
2
解决办法
9977
查看次数

标签 统计

jestjs ×1

node.js ×1