I get the following error on running npm test on my project, not created with create-react-app:
ReferenceError: expect is not defined
at Object.<anonymous> (/Users/ryedida/Desktop/threaded-messenger/node_modules/@testing-library/jest-dom/dist/extend-expect.js:7:1)
at Module._compile (internal/modules/cjs/loader.js:1256:30)
...
at require (internal/modules/cjs/helpers.js:75:18)
at Object.<anonymous> (/Users/ryedida/Desktop/threaded-messenger/src/componentTestUtils.js:1:1)
Setup
My root directory has a jest.config.js file, whose contents are
const config = {
verbose: true,
setupFilesAfterEnv: ['<rootDir>/src/componentTestUtils.js'],
testEnvironment: "jsdom"
};
module.exports = config;
componentTestUtils.js has
import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import { MemoryRouter, Route } from 'react-router-dom';
import { render } from '@testing-library/react';
import App from '../components/App';
and defines some functions that I use. I am using Node 14.7, npm 7.6.3, @testing-library/jest-dom 5.12.0, @testing-library/react 11.2.6. My test script in package.json is
mocha --require @babel/register --reporter progress components/*.test.js
Similar Questions/Issues
My research in this issue has led me to
- this GitHub issue in Enzyme, where a highly voted answer essentially says add the
setupFilesAfterEnvkey in the jest config - this GitHub issue in jest-dom, where the recommendations to upgrade
@testing-library/jest-domand@testing-library/reactdon't apply since my versions are higher, and their recommendation to upgrade from Node 10 to 12 also doesn't apply. Their other recommendation to add the same key above also did not work. - this GitHub issue in jest-native, the same
setupFilesAfterEnvrecommendation - this SO question with the same issue, but I already have the import in the accepted answer.
How do I solve this error?