Skip to content

Instantly share code, notes, and snippets.

@brianbancroft
Created February 9, 2022 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianbancroft/46aa2628985b2feb9d15497433cbf631 to your computer and use it in GitHub Desktop.
Save brianbancroft/46aa2628985b2feb9d15497433cbf631 to your computer and use it in GitHub Desktop.
Integrate Jest & React Testing Library in a React Vite Project.

Integrate Jest & React Testing Library in a React Vite Project

  1. 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
  1. 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"
        ]
      }
    }
  }
  1. Create a jest directory in the root path of the project, then create another directory called mocks inside jest directory
  2. Inside mocks directory create a cssMock.js file with this code
module.exports = {
  process() {
    return 'module.exports = {};';
  },
  getCacheKey() {
    return 'cssTransform';
  },
};
  1. Create a jest.setup.js file inside mocks directory with the imports that we need
import '@testing-library/jest-dom';
  1. 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"
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment