reactjstypescriptunit-testingjestjs

How to fix "React is not defined" in Jest tests for a TypeScript React project?


I'm writing Jest tests for a React project that uses TypeScript. When I run the tests, I get the following error:

ReferenceError: React is not defined

I was able to get rid of this error by adding:

import React from "react";

However, this causes a TypeScript warning during build:

'React' is declared but its value is never read. ts(6133)

To silence the warning, I added:

// @ts-ignore
import React from "react";

And I have tried this: https://stackoverflow.com/a/55461138/16441779 but this didn't work for me.

This works, but is there a cleaner or more good way to solve this issue without suppressing TypeScript errors?


Solution

  • Add this to your jest.config.js or setupTests.ts

    global.React = require("react");
    

    Also add below to your tsconfig.json

    "types": ["jest", "node"]
    

    There's no need to import React in each file or use @ts-ignore.