6

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;

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

// 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` option):
    functions/src/classes/__tests__/ScriptTag.test.ts:173:11 - error TS2339: Property 'mockResponseOnce' does not exist on type '(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>'.

    173     fetch.mockResponseOnce(JSON.stringify(1));
                  ~~~~~~~~~~~~~~~~
    functions/src/classes/__tests__/ScriptTag.test.ts:174:24 - error TS2349: This expression is not callable.
      Type 'typeof import("/home/owner/PhpstormProjects/shopify/buyUsedServer/node_modules/jest-fetch-mock/types/index")' has no call signatures.

    174     const data = await fetchMock("x");
                               ~~~~~~~~~

Test Suites: 1 failed, 1 total
  • 当我注释掉该测试的违规行并将其标记为 .skip() 时,我得到 1 次跳过,7 次通过。这是一个线索,表明问题似乎首先出现在这个测试套件上,即使它位于测试文件的底部,并且应该最后测试,结果仍然会为其他人累积。
  • 我还注意到没有@types/jest-fetch-mock,我认为它是不需要的。
  • 我没有将 isomorphic-fetch 导入到测试文件中。然而,它被导入到目标文件“ScriptTag.ts”中。我希望 Jest 使用它指定的全局设置覆盖该库。

有谁知道如何解决这个问题?

4

0 回答 0