Skip to content

Instantly share code, notes, and snippets.

@Christopher96u
Last active August 18, 2022 00:50
Show Gist options
  • Select an option

  • Save Christopher96u/5708ad2a155fbe67df4b3a0d120c0d34 to your computer and use it in GitHub Desktop.

Select an option

Save Christopher96u/5708ad2a155fbe67df4b3a0d120c0d34 to your computer and use it in GitHub Desktop.
Config your test enviroment with Jest + React Testing Library for your React Projects

Install and configure Jest + React Testing Library

For React + Vite projects

  1. Install:
yarn add --dev jest babel-jest @babel/preset-env @babel/preset-react 
yarn add --dev @testing-library/react @types/jest jest-environment-jsdom
  1. Optional: If we use Fetch API in our project:
yarn add --dev whatwg-fetch
  1. Update the scripts in package.json
"scripts: {
  ...
  "test": "jest --watchAll"
  1. Create the configuration from babel babel.config.js
module.exports = {
    presets: [
        [ '@babel/preset-env', { targets: { esmodules: true } } ],
        [ '@babel/preset-react', { runtime: 'automatic' } ],
    ],
};
  1. Optional, but sometimes it's necessary, create Jest config and setup:

jest.config.js

module.exports = {
    testEnvironment: 'jest-environment-jsdom',
    setupFiles: ['./jest.setup.js']
}

jest.setup.js

// In case we need to set up Fetch API
import 'whatwg-fetch'; // <-- yarn add whatwg-fetch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment