I'm learning to write a test for my react typescript app and come across this problem. I tried to use many different methods I found on internet but nothing work, the error is
Test suite failed to run
ReferenceError: expect is not defined
at Object.<anonymous> (node_modules/@testing-library/jest-dom/dist/extend-expect.js:7:1)
at Object.<anonymous> (node_modules/@testing-library/jest-dom/extend-expect.js:2:1)
This is my App.test.tsx file. Where error occur.
import React from 'react';
import App from './App';
import {render, fireEvent, waitFor, screen} from '@testing-library/react'
import "@testing-library/jest-dom/extend-expect";
import '@testing-library/jest-dom'
test('renders learn react link',async () => {
let screen = render(<App></App>);
expect(screen.getByText(/Hello/i)).toBeInTheDocument()
});
My package.json file
{
"dependencies": {
"@emotion/react": "^11.7.1",
"@emotion/styled": "^11.6.0",
"@fontsource/roboto": "^4.5.1",
"@mui/material": "^5.2.7",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^7.1.2",
"@types/jest": "^27.4.0",
"@types/node": "^17.0.8",
"@types/react": "^17.0.38",
"@types/react-dom": "^17.0.11",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1",
"ts-jest": "^27.1.2",
"typescript": "^4.5.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"devDependencies": {
"@babel/preset-env": "^7.16.7",
"@babel/preset-react": "^7.16.7",
"babel-jest": "^27.4.6",
"jest": "^27.4.7",
"react-test-renderer": "^17.0.2"
}
}
And these are my jest.config.js and bebel.config.js file (Not sure if this matter)
module.exports = {
roots: ["<rootDir>/src"],
testMatch: [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)",
],
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
},
coveragePathIgnorePatterns: [
"/node_modules/"
],
moduleNameMapper: {
"\\.(css|less)$": "identity-obj-proxy",
},
"setupFiles": [
"<rootDir>/src/setupTests.ts"
]
};
module.exports = function (api) {
const presets = [
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-flow'
];
const plugins = [
'@babel/plugin-transform-runtime',
];
api.cache(false);
return {
presets,
plugins
};
};
delete node_modules directory and do npm install
also replace the "setupFiles" with setupFilesAfterEnv in jest.config.js like following
setupFilesAfterEnv: [
'./setupTests.js',
],
try this in App.test.tsx
import React from 'react';
import App from './App';
import {render, fireEvent, waitFor, screen} from '@testing-library/react'
test('renders learn react link',async () => {
let screen = render(<App/>);
expect(screen.getByText(/Hello/i)).toBeInTheDocument()
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With