相关疑难解决方法(0)

如何通过 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
查看次数

fetch-mock不模拟我的提取

这是代码片段:

var fetch = require("node-fetch");
var fetchMock = require("fetch-mock");

function setupMockBlockChainExplorer() {
  fetchMock.mock("https://cardanoexplorer.com/api/addresses/summary/DdzFFzCqrhsmagp4fDZpcY9UaBJk4Z8GaDfxqMCSwxPs3PnVoXmJWUZcgAxw3diCHVYauontEfk7YGeAu2LvAwq3aG2XQ8Mtsz7Vc8LA", {
    "status" : 200,
    "body" : "override"
  });
}

async function makeRequest(url, method = "get", body = null, headers = null) {
  const res = await fetch(url, {
    method: method,
    headers: headers,
    body: body,
  });

  return res.json()
};

setupMockBlockChainExplorer();

var req = makeRequest("https://cardanoexplorer.com/api/addresses/summary/DdzFFzCqrhsmagp4fDZpcY9UaBJk4Z8GaDfxqMCSwxPs3PnVoXmJWUZcgAxw3diCHVYauontEfk7YGeAu2LvAwq3aG2XQ8Mtsz7Vc8LA");

// I would expect it to print "override" but it prints the http response from the real request instead
req.then(console.log)
Run Code Online (Sandbox Code Playgroud)

因此,正如您在上面的代码中看到的那样,我试图覆盖HTTP请求,但是我仍然使用fetch来访问真实的URL。我已经阅读了fetch-mock文档(http://www.wheresrhys.co.uk/fetch-mock/installation.html),并且还尝试过这样的配置:

fetchMock.config …
Run Code Online (Sandbox Code Playgroud)

fetch node.js fetch-mock

6
推荐指数
1
解决办法
3295
查看次数

带有 Typescript 的“jest-fetch-mock”:“没有调用签名”和“对象上不存在”错误

jest-fetch-mock 有一个我遵循的 Typescript 设置指南:https ://www.npmjs.com/package/jest-fetch-mock

// package.json
, "devDependencies": {
    "@types/jest": "^24.0.23",
    "jest": "^24.9.0",
    "jest-fetch-mock": "^2.1.2",
    "ts-jest": "^24.2.0",
    "typescript": "^3.7.2"
  },
  "jest": {
    "automock": false,
    "setupFiles": ["./setupJest.ts"]
  }

// setupJest.ts
import {GlobalWithFetchMock} from "jest-fetch-mock";

const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock;

customGlobal.fetch = require('jest-fetch-mock');
customGlobal.fetchMock = customGlobal.fetch;
Run Code Online (Sandbox Code Playgroud)

但是当我尝试设置一个虚拟的解析值时:

// ScriptTag.test.ts
  test("", async () => {
    fetch.mockResponseOnce(JSON.stringify(1));
    const data = await fetchMock("x");

    await expect(data.json()).resolves.toStrictEqual(2);
  })

// terminal
 FAIL  functions/src/classes/__tests__/ScriptTag.test.ts
  ? Test suite failed to run

    TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` …
Run Code Online (Sandbox Code Playgroud)

fetch typescript jestjs jest-fetch-mock

6
推荐指数
0
解决办法
697
查看次数