Jest is not defined
Asked Answered
W

1

6

I'm currently making a react app with typescript, and I'm testing using react-testing-library. The app crashes with ReferenceError: jest is not defined. All of my tests pass though.

Previously, everything was working. The only thing that has changed is I reorganized a few files.

Code:

import { FormProps } from "../containers";

const onChange = jest.fn(); // The problem
const history: any = jest.fn();
const location: any = jest.fn();
const match: any = jest.fn();

const TestProps: FormProps = {
  onChange,
  history,
  location,
  match,
};

export default TestProps;
Witted answered 14/3, 2019 at 18:50 Comment(3)
Is this code used in your app? jest is defined as a global when tests are run using Jest, but otherwise it doesn't exist and should never be used in code run in the app.Mozellamozelle
No it's not, but I rewrote my tests to grab directly from this file instead of the index of the folder this is in, and everything works now. Thank you for your helpWitted
Cool, glad it's workingMozellamozelle
I
0

The jest global is only ever defined during tests. It's added in by the Jest test runner.

As mentioned in the OP's comments, always make sure that any references to test-only globals such as jest only happen in test files. If your runtime code includes a reference to a jest global, then that'll crash at runtime because the Jest isn't being used to run your app.

If you're seeing crashes referring to a jest global then it means your runtime code is accidentally importing from test code. Makes sure runtime files never import anything with jest globals - even transitively (e.g. App.tsx importing shared.ts importing tests.ts, where tests.ts uses jest).

Irresolute answered 9/1, 2024 at 9:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.