[英]React Testing library custom setup import test-utils: module not installed. Unable to resolve path
I'm trying to configure jest absolute path for my custom test-utils directory ( https://testing-library.com/docs/react-testing-library/setup#configuring-jest-with-test-utils ), but I get the error Cannot find module 'test-utils' / unable to resolve path我正在尝试为我的自定义 test-utils 目录( https://testing-library.com/docs/react-testing-library/setup#configuring-jest-with-test-utils )配置 jest 绝对路径,但我得到错误找不到模块'test-utils'/无法解析路径
My folder tree我的文件夹树
-src/
--utils/
---test-utils/
----test-utils.js
----custom-queries.js
-jest.config.js
-jsconfig.json
My jest.config.js我的 jest.config.js
module.exports = {
transform: {
'^.+\\.jsx?$': 'babel-jest',
},
testEnvironment: 'jsdom',
moduleNameMapper: {
'\\.(css|less)$': 'identity-obj-proxy',
},
moduleDirectories: [
'node_modules',
'src',
'utils',
'test-utils',
],
};
My jsconfig.json我的 jsconfig.json
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"test-utils": ["./utils/test-utils"]
}
},
"include": ["src"],
"exclude": ["node_modules"]
}
My component test我的组件测试
import { render } from 'test-utils';
import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import Alert from './alert';
describe('Alert', () => {
test('Renders Alert component', () => {
const { getByRole } = render(<Alert message="Success!" />);
const alert = getByRole(/alert/);
expect(alert).toHaveTextContent('Success!');
});
});
The test-utils
is your custom module for which you specify path alias and how to resolve it in jsconfig.json
as follows: test-utils
是您的自定义模块,您可以为其指定路径别名以及如何在jsconfig.json
中解析它,如下所示:
"compilerOptions":{
"baseUrl":"src",
"paths":{
"test-utils": ["./utils/test-utils"]
}
}
The same way you need to tell to Jest how to resolve it with moduleNameMapper
option in your jest.config.js
as follows:您需要以同样的方式告诉 Jest 如何使用
jest.config.js
中的moduleNameMapper
选项解决它,如下所示:
moduleNameMapper: {
'test-utils/(.*)": "<rootDir>/src/utils/test-utils/$1',
},
For official documentation see: https://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring官方文档见: https ://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring
For similar issues see: Jest not finding alias path , React: Jest configuration Issue with Path Aliases and How to use path alias in a react project with Typescript + Jest对于类似的问题,请参阅: Jest not found alias path 、 React: Jest configuration Issue with Path Aliases 和How to use path alias in a react project with Typescript + Jest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.