Testing with Jest using React Craco
React with Webpack and Craco
We started a React App way back in the day. Before React hooks were even a thing. So Create React App was the de facto way of creating a react app. But then as time went on Tailwind was the next hot thing (for good reason as well I absolutely love it). This meant we had to update to using craco instead of react-scripts. Essentially Craco just felt like a patch over react-scripts and has caused me some minor inconveniences when setting up Jest. A lot of articles would say how to config Jest in a certain way, but it was always slightly different in CRACO. So I hope this article helps the next person who is in my current situation.
TLDR: This is guide for setting up Jest is only React with a CRACO setup.
Installation
Firstly install the following
yarn add jest
yarn add ts-jest
craco.config.js configuration
This is where we put the config for jest. Note that moduleNameMapper is pretty important if you use alias mapping for importing paths.
const jestConfig = {
configure: {
preset: 'ts-jest',
verbose: true,
transform: {
'^.+\\.ts?$': 'ts-jest',
'^.+\\.(js|jsx)$': 'babel-jest',
},
transformIgnorePatterns: ['/node_modules/'],
moduleNameMapper: {
'^@(.*)$': '<rootDir>/src', // should to match the {webpack: alias} config
},
},
};
Now under module.exports you can use the jestConfig
module.exports = {
jest: jestConfig
... all your other webpack config goes here
}
Create a test
Inside your src folder create a test folder to encapsulate all your tests in one location. Then make contextual folders based on what you are testing. Then within a file like context.test.ts
describe('Overall description for test', () => {
it('Does a specific unit test', async () => {
const result = await getData()
expect(result).toEqual(resultAfterConversion);
});
});