Skip to content

Instantly share code, notes, and snippets.

@kapiljhajhria
Created October 19, 2021 13:25
Show Gist options
  • Save kapiljhajhria/fa3b49cb59e6c7c617247c79c73ca94f to your computer and use it in GitHub Desktop.
Save kapiljhajhria/fa3b49cb59e6c7c617247c79c73ca94f 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