7

jest-fetch-mock has a Typescript setup guide which I've followed: 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;

But then when I try to set a dummy resolved value:

// 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
  • When I comment out the offending lines for that test, and mark it as .skip(), then I get 1 skip, 7 passes. This is a clue that the problem seems to occur first on this test suite even though it is at the bottom of the test file and should be tested last with results still accruing for the others.
  • I also notice there is no @ types/jest-fetch-mock, I assume it isn't needed.
  • I'm not importing isomorphic-fetch into the test file. It is being imported into the target file "ScriptTag.ts" however. I would expect Jest to override that library with the global settings it specified.

Anyone know how to resolve this?

Sean D
  • 3,810
  • 11
  • 45
  • 90

0 Answers0