Search code examples
typescriptunit-testingreact-nativejestjsjest-fetch-mock

React Native with TypeScript: How to set up globals in setup.js?


I'm building a React Native app with TypeScript.

I want to use jest-fetch-mock. In the documentation it says to create setup.js file and add

global.fetch = require("jest-fetch-mock");

in it. I did that. But I get the error:

[ts] Cannot compile namespaces when the '--isolatedModules' flag is provided.

So I googled and found out that I just have to import something to fix this (which is fine, since I need imports for setting NativeModules.ReactLocalization for using localization anyway).

Then I get the error:

[ts] Cannot find name 'global'.

So I googled some more and found this 'fix':

// Change to file to setup.ts and
const globalAny: any = global;

But it throws the same error and now I'm stuck. How can I set a global variable?


Solution

  • Why typescript compiles .js files?

    If you have setup.ts file: try to add declare var global: any; before global.fetch = ....

    However, I suggest you to use typings for your project:

    npm i -D @types/node @types/jest
    

    Then extending global object will look like this:

    declare module NodeJS {
      interface Global {
        fetch: GlobalFetch
      }
    }
    
    global.fetch = require('jest-fetch-mock');