0

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?

2
  • 1
    Please, show jest, babel and ts configs, they are relevant. One part of the problem is that "'React' is declared but its value is never read" is not a real error, it's because ts is configured to disallow unused vars. Generally a linter is a more suitable tool for this purpose, it can be configured to exclude things like React from the rule Commented Jun 13 at 9:29
  • It may be that your jsx configuration for tests doesn't match the one you use while compiling. Note how react-jsx uses a helper function while react uses React.createElement which would error with that exact error if React is not in scope Commented Jun 14 at 8:05

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.