Skip to content

Instantly share code, notes, and snippets.

@Syden10
Forked from Klerith/vite-testing-config.md
Created June 23, 2024 18:38
Show Gist options
  • Select an option

  • Save Syden10/8810e7ae657d6b43a2e2328b0dc24676 to your computer and use it in GitHub Desktop.

Select an option

Save Syden10/8810e7ae657d6b43a2e2328b0dc24676 to your computer and use it in GitHub Desktop.
Vite + Jest + React Testing Library - Configuraciones a seguir

Instalación y configuracion de Jest + React Testing Library

En proyectos de React + Vite

  1. Instalaciones:
yarn add --dev jest babel-jest @babel/preset-env @babel/preset-react 
yarn add --dev @testing-library/react @types/jest jest-environment-jsdom
  1. Opcional: Si usamos Fetch API en el proyecto:
yarn add --dev whatwg-fetch
  1. Actualizar los scripts del package.json
"scripts: {
  ...
  "test": "jest --watchAll"
  1. Crear la configuración de babel babel.config.js
module.exports = {
    presets: [
        [ '@babel/preset-env', { targets: { esmodules: true } } ],
        [ '@babel/preset-react', { runtime: 'automatic' } ],
    ],
};
  1. Opcional, pero eventualmente necesario, crear Jest config y setup:

jest.config.js

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

jest.setup.js

// En caso de necesitar la implementación del FetchAPI
import 'whatwg-fetch'; // <-- yarn add whatwg-fetch
@Syden10
Copy link
Author

Syden10 commented Jun 23, 2024

Change babel config filename to: babel.config.cjs
Change jest config filename to: jest.config.cjs

@Syden10
Copy link
Author

Syden10 commented Jun 25, 2024

Add environment to the top of the test file:

/** @jest-environment jsdom */
//test code

Also install jsdom independently: yarn add -D jest-environment-jsdom

@Syden10
Copy link
Author

Syden10 commented Jun 25, 2024

For module is not defined error: https://stackoverflow.com/questions/64914701/jest-module-not-defined

Change jest.config.js from:

module.exports = {
  /* config here */
}

to

export default {
  testEnvironment: 'jest-environment-jsdom',
  setupFiles: ['./jest.setup.js'],
  /* more config here */
};

Change babel.config.js to babel.config.json with:

{
  "presets": [
    ["@babel/preset-env", { "targets": { "esmodules": true } }],
    ["@babel/preset-react", { "runtime": "automatic" }]
  ]
}

@Syden10
Copy link
Author

Syden10 commented Jun 25, 2024

For describe and test not defined error: https://stackoverflow.com/questions/44611190/using-jest-in-my-react-app-describe-is-not-defined

Add the following to your .eslintrc.cjs file:

"env": {
    "jest": true
}

@Syden10
Copy link
Author

Syden10 commented Jul 9, 2024

For testing-library/dom not found, run:

yarn add --dev @testing-library/react @testing-library/dom

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment