【发布时间】:2022-01-09 04:15:06
【问题描述】:
我正在学习为我的 react typescript 应用程序编写测试,并遇到了这个问题。我尝试使用在互联网上找到的许多不同方法,但没有任何效果,错误是
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)
这是我的 App.test.tsx 文件。发生错误的地方。
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()
});
我的 package.json 文件
{
"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"
}
}
这些是我的 jest.config.js 和 bebel.config.js 文件(不确定是否有问题)
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
};
};
【问题讨论】:
标签: reactjs jestjs react-testing-library