Set Up Jest Environment
Topic | Source |
---|---|
🧩 React | me |
Setting up Jest can be hard. This should be a good start.
When setting up your environment to test with Jest, there are a couple of caveats that you need to take care of.
I had trouble configuring everything properly. From importing CSS files, modules, JS files or components into your tests, to using JSX in your tests and finally testing API calls with mock-fetch, it took some time to get it right.
I hope that this summary is correct, but cannot guarantee it, since I created it after finishing everything and testing a lot. This might need to be adjusted when I set it up the next time.
Npm Modules
npm install --save-dev @babel/preset-env @babel/preset-react @testing-library/react @testing-library/jest-dom @testing-library/user-event babel-jest identity-obj-proxy jest jest-environment-jsdom jest-fetch-mock msw react-test-renderer ts-jest ts-node
Config
jest.config.ts
import type { Config } from 'jest'
const config: Config = {
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest",
},
moduleNameMapper: {
"\\.(css|sass)$": "identity-obj-proxy",
},
rootDir: "./",
modulePaths: [ "<rootDir>" ],
moduleDirectories: ["node_modules", "src"],
moduleFileExtensions: [ "js", "ts", "tsx", "json" ],
testEnvironment: "jest-environment-jsdom",
"automock": false,
"setupFiles": [ // currently used for jest-fetch-mo
"./setupJest.js"
]
}
export default config;
babel.config.cjs
module.exports = {
presets: [
'@babel/preset-react',
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
setupJest.js
require('jest-fetch-mock').enableMocks()
Needed to use fetch in Jest and test mock APIs