我已经安装了'@testing-library/jest-dom',所以应该在那里。还有下面的进口,我的配置有什么问题吗?
TypeError: expect(...).toBeInTheDocument is not a function
52 | renderIt(onSubmit);
53 |
> 54 | expect(screen.getByText(/alberta/i)).toBeInTheDocument();我的测试:
import { render, screen } from '@testing-library/react';
import { Formik, Form } from 'formik';
import { Select } from '.';
const options = [
'Alberta',
'British Columbia',
'Manitoba',
'New Brunswick',
'Newfoundland & Labrador',
'Northwest Territories',
'Nova Scotia',
'Nunavut',
'Ontario',
'Prince Edward Island',
'Quebec',
'Saskatchewan',
'Yukon',
];
const renderIt = (onSubmit: () => void) => render(
<Formik
initialValues={{ province: '' }}
onSubmit={onSubmit}
>
<Form>
<Select name="province" options={options} />
</Form>
</Formik>,
);
describe('Select component', () => {
test('It renders', () => {
const onSubmit = jest.fn();
renderIt(onSubmit);
expect(screen.getByText(/alberta/i)).toBeInTheDocument();
});
});我的src/setupTests.ts文件:
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';package.json
"devDependencies": {
"@testing-library/dom": "8.11.3",
"@testing-library/jest-dom": "5.16.2",
"@testing-library/react": "^13.0.0-alpha.6",
"@testing-library/react-hooks": "7.0.2",
"@testing-library/user-event": "13.5.0",
"@types/jest": "27.4.1",
"jest": "27.5.1",
"ts-jest": "27.1.3",
"typescript": "4.6.2"
},jest.config.js
module.exports = {
testEnvironment: 'jsdom',
preset: 'ts-jest',
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/fileMock.js',
'\\.(css|less)$': 'identity-obj-proxy',
},
};发布于 2022-03-23 16:43:07
您应该使用setupTests.ts属性在jest配置中声明setupFilesAfterEnv。
jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
preset: 'ts-jest',
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/fileMock.js',
'\\.(css|less)$': 'identity-obj-proxy',
},
};https://stackoverflow.com/questions/71589882
复制相似问题