I am trying set up tests with Jest
in a create-react-app
that is using the override
function from customize-cra
and react-app-rewired
. I have set up a relative path alias and when I run tests it throwing the error cannot find module
here is the code...
// LoginForm.test.js
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import LoginForm from './LoginForm';
it('submits', () => {
const onSubmit = jest.fn();
const { getByText } = render(<LoginForm onSubmit={onSubmit} />);
fireEvent.click(getByText('Log in'));
expect(onSubmit).toHaveBeenCalled();
});
// config-overrides.js
const {
override,
fixBabelImports,
addLessLoader,
addBabelPlugin
} = require("customize-cra");
module.exports = override(
fixBabelImports("import", [
{
libraryName: "antd",
libraryDirectory: "es"
// style: true,
},
{
libraryName: "ant-design-pro",
libraryDirectory: "lib"
// style: true,
}
]),
addBabelPlugin([
"babel-plugin-root-import",
{
rootPathSuffix: "./src"
}
]),
addLessLoader({
javascriptEnabled: true,
modifyVars: {
"@select-item-selected-font-weight": "500",
"@font-family":
'"Futura W01", "Futura", -apple -system, BlinkMacSystemFont, "Segoe UI", sans-serif',
"@pagination-font-family":
'"Futura W01", "Futura", -apple -system, BlinkMacSystemFont, "Segoe UI", sans-serif',
"@statistic-font-family":
'"Futura W01", "Futura", -apple -system, BlinkMacSystemFont, "Segoe UI", sans-serif'
}
})
);
Any pointers much appreciated, thank you.
This is maybe a bit old but I just came across it and solved it so maybe it can help other people.
React app rewired uses react-scripts under the hood so it will not pick up your webpack configuration files. However there is a way to customize it, you can put your jest configuration in the root of your package.json:
"jest": {
"moduleNameMapper": {
"^@app(.*)$": "<rootDir>/src/ui/app$1"
},
"setupFiles": [
"<rootDir>/config/jest/setupTests.js"
]
}
You can see that react-script is picking up this config if you go to the source code of react-scripts/scripts/test and see that it is creating the jest config:
const createJestConfig = require('./utils/createJestConfig');
And that file overrides the default configuration with the jest config in your package.json:
const overrides = Object.assign({}, require(paths.appPackageJson).jest);
Where paths.appPackageJson is your package.json
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