Skip to content

Instantly share code, notes, and snippets.

@Klerith
Last active July 22, 2024 19:01
Show Gist options
  • Save Klerith/ca7e57fae3c9ab92ad08baadc6c26177 to your computer and use it in GitHub Desktop.
Save Klerith/ca7e57fae3c9ab92ad08baadc6c26177 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
@DavidPerezHz
Copy link

DavidPerezHz commented Sep 18, 2023

export default { testEnvironment: 'jest-environment-jsdom', setupFiles: ['./jest.setup.js'] }

Esto me funciono gracias

Gracias... esto faltaba para permitir utilizar esta expresión

import { renderHook } from "@testing-library/react";

En ves de utilizar require("@testing-library/react")

@MiguelMateoTavarez
Copy link

MiguelMateoTavarez commented Oct 3, 2023

Realice la configuración

image

@JRIVERADDIAZ
Copy link

JRIVERADDIAZ commented Oct 9, 2023

for all those whom has issues setting the enviroment along jest and react testing library, you should not use the "commonjs" : "module" at the package.json if the files created has the .js file type assigned, once you check that, you should match the dependencies on the original package.json file made by Fernando H. attached at the end of the lesson seccion 5, and run the next commnads on yarn , yarn install --inmmutable , yarn clean cache , yarn bin , yarn test this willl works. cause if you wants to use the common js the solution for all those errors is to switch npm and manage the babel configs} for a better set experience.

@Alejgl04
Copy link

Alejgl04 commented Dec 2, 2023

Hola comunidad les comparto que tambien tuve los mismos errores que la mayoria de ustedes, les compartire cada unos de mis archivos por si alguien lo necesita. Estos son mis settings segun cada archivo solo tuve que cambiar una extension y fue en babel js a cjs y en el "eslintrc.js" agregue node=true (segun internet) "env: { browser: true, node: true, es2020: true}" y en los plugins agregue " plugins: ['react-refresh', 'jest'],
"

babel
image
image
image

@JasubiPL
Copy link

Realice la configuración como lo indicas pero me arrojo el siguiente error, image

Hola hay una solución sobre eso. cambia el nombre del archivo bablel.config.js a babel.config.cjs y haz lo mismo con el archivo de jes.config.js; cambialo a jest.config.cjs. Es lo que soluciono -> Fernando que esta en las sección de preguntas. Seria bueno que actualice esto en el readme. @Klerith Es solo una sugerencia. jejeje

Yo tambien lo pude solucionar en el package.json donde "name": "journal-app", "private": true, "version": "0.0.0", debajo de esta linea aparece algo de module y eso lo borre, dejandolo asi { "name": "journal-app", "private": true, "version": "0.0.0", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview", "test": "jest --watchAll" },

Solo nececitas cambiar la extencion "jest.config.js" a "jest.config.cjs

@judaaaron
Copy link

Funciona, gracias

@EfededeCe
Copy link

EfededeCe commented Feb 22, 2024

Hola!! Quería comentar que tuve un problema con el testing a la hora de hacer los test a componentes, me aparecían los problemas antes mencionados por algunos de ustedes como el de los ".cjs" pero además me lanzaba un error: ReferenceError: React is not defined
Captura desde 2024-02-22 13-55-43
y encontré este post en StackOverflow
y agregando unas lineas de código en el archivo jest.setup.js me funcionó:

jest.setup.js :

import 'whatwg-fetch';
import React from 'react';
global.React = React;

@CarolinaOjcius
Copy link

CarolinaOjcius commented Mar 19, 2024

Además del instructivo para que me funcionara tuve que cambiarle la extensión al jest.config.js a jest.config.cjs, también el babel.config.js a babel.config.cjs y ejecutar el comando yarn add -D jest-environment-jsdom

@cquesadad
Copy link

cjs

Genial! Me ha funcionado con solo ese cambio

@AlanDev24
Copy link

Si aun tienes problemas incluso despues de cambiar la extencion a cjs, puede que estes usando una version mas actual y debes agregar "module:true" en el archivo .eslint.cjs
module.exports = {
root: true,
env: { browser: true, es2020: true, module: true },
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
settings: { react: { version: '18.2' } },
plugins: ['react-refresh'],
rules: {
'react/jsx-no-target-blank': 'off',
'react/prop-types': 'off',
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
imagen_2024-04-03_223854586

@DavidGRamiro
Copy link

DavidGRamiro commented May 11, 2024

No me autocompleta absolutamente nada de JEST, alguna solución ? Librerías instaladas, y todo corriendo, TEST pasan, pero por ejemplo, en los expect(). -> No me da absolutamente ninguna ayuda al método que quiero utilizar y tengo que escribirlo a mano .

Demasiado complicado utilizar JEST con todas las configuraciones que tiene. Estoy seguro de que tienen que existir alternativas. Con esto solo se consigue que no quiera hacer absolutamente ninguna prueba.

Conseguido. Investigando por StackOverFlow. A nivel root del proyecto o de la carpeta test, hay que crear un archivo, llamado jsconfig.js.
Dentro de este, añadir

{ "typeAcquisition": { "include": [ "jest" ] } }

@Laura-Urb
Copy link

Dejo esto para los que tienen memoria de pajarito, son vagos para escribir como yo, y tiene que estar buscando constantemente el equivalente en npm:
Instalaciones:
npm install jest babel-jest @babel/preset-env @babel/preset-react --save-dev
npm install @testing-library/react @types/jest jest-environment-jsdom --save-dev
Opcional:
Si usamos Fetch API en el proyecto:
npm install whatwg-fetch --save-dev

@eugeniopch
Copy link

npm install jest babel-jest @babel/preset-env @babel/preset-react --save-dev
npm install @testing-library/react @types/jest jest-environment-jsdom --save-dev

Muchas gracias Laura-Urb!

@blaragdev
Copy link

hola, estoy haciendo el curso y pase por todos los errores que mencionan arribas + otros que fueron reflejados por otros compañeros en udemy. Dare mis configuraciones por si alguien las necesita.

1.- instalaciones (npm):


npm install jest babel-jest @babel/preset-env @babel/preset-react --save-dev

npm install @testing-library/react @types/jest jest-environment-jsdom --save-dev

npm install whatwg-fetch --save-dev

npm i --save-dev @types/whatwg-fetch"

npm i prop-types

2.- crear y cambiar extensiones:
babel.config.js a babel.config.cjs

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

jest.config.cjs (crear si no existe con las configuraciones)

module.exports = {
  testEnvironment: "jest-environment-jsdom",
  setupFiles: ["./jest.setup.cjs"],
};

jest.setup.cjs (crear si no existe con las configuraciones necesarias)

module.exports = require("whatwg-fetch");

Saludos!

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