Anas
Anas

Reputation: 1503

React and Typescript - Tests are failing due to type error "Conversion of type 'Global & typeof globalThis' to type 'GlobalWithFetchMock'..."

Working with React and Typescript is fantastic, but can sometimes result in head-scratching issues. In this case all my test failed with the same error related to jest-fetch-mock:

> NODE_ENV=test jest
 FAIL  src/store/index.test.tsx
  ● Test suite failed to run
    src/setupTests.ts:6:43 - error TS2352: Conversion of type 'Global & typeof globalThis' to type 'GlobalWithFetchMock' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
      Property 'fetchMock' is missing in type 'Global & typeof globalThis' but required in type 'GlobalWithFetchMock'.
    6 const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock
                                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      node_modules/jest-fetch-mock/types/index.d.ts:15:5
        15     fetchMock: FetchMock;
               ~~~~~~~~~
        'fetchMock' is declared here.

There had been no change in the setupTests.ts file, so perhaps it would be caused by an update of some dependency. I tried deleting the node_modules and reinstall, clearing cache and changing node version, but nothing changed.

Upvotes: 0

Views: 2446

Answers (1)

Anas
Anas

Reputation: 1503

If you declared GlobalWithFetchMock as a global in setUpTests.ts and Typescript is still complaining try to wrap the global type in brackets "()" and set initially as unknown

Amend from

const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock

to

const customGlobal: GlobalWithFetchMock = (global as unknown) as GlobalWithFetchMock

You should be able to run your test again successfully with lots of green:)

Upvotes: 3

Related Questions