Integrate Jest & React Testing Library in a React Vite Project
Install Dependencies
yarn add --dev jest babel-jest @babel/preset-env @babel/core @babel/plugin-syntax-jsx @babel/preset-react @testing-library/dom @testing-library/jest-dom @testing-library/react @testing-library/user-event babel-preset-react-app identity-obj-proxy jest-circus jest-scss-transform jest-watch-typeahead
Set Jest & babel configs in package.json
"jest": {
"roots": [
"<rootDir>/src"
],
"setupFilesAfterEnv": [
"<rootDir>/jest/mocks/jest.setup.js"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"testEnvironment": "jsdom",
"transform": {
"^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.scss$": "jest-scss-transform",
"^.+\\.css$": "<rootDir>/jest/mocks/cssMock.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$",
"^.+\\.module\\.(css|sass|scss)$"
],
"moduleNameMapper": {
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
],
"resetMocks": true
},
"babel": {
"env": {
"test": {
"presets": [
"react-app"
]
}
}
}
Create a jest
directory in the root path of the project, then create another directory called mocks
inside jest
directory
Inside mocks
directory create a cssMock.js
file with this code
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
return 'cssTransform';
},
};
Create a jest.setup.js
file inside mocks
directory with the imports that we need
import '@testing-library/jest-dom';
Create a .babelrc
file in the src
directory of the project with the next configuration
{
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-private-methods"
],
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}