Skip to content

Instantly share code, notes, and snippets.

@Klerith
Last active March 27, 2024 17:18
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
@grmnfrnndz
Copy link

Thanks You !!!

@MicrobotsMx
Copy link

Maravilloso aporte profe. Para los que trabajan con npm y para los que hayan tenido también problemas con las configuraciones, hice esta guía: https://shard-pull-4e1.notion.site/Day-15-of-100daysofcode-b4f62b40aa804d5b91d6ecfcc5a761f6

a mi me funciono tu guia al 100, mil gracias

@johinner
Copy link

De maravilla

@AlexProcess
Copy link

Maravilloso aporte profe. Para los que trabajan con npm y para los que hayan tenido también problemas con las configuraciones, hice esta guía: https://shard-pull-4e1.notion.site/Day-15-of-100daysofcode-b4f62b40aa804d5b91d6ecfcc5a761f6

Eres un ser de luz amigo =)

@Mushroom0047
Copy link

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

Esto me funciono gracias

@alischmidt
Copy link

Si alguien tiene error con la configuración del test, cambie los config de babel y jest con extensión.cjs. Ej: "babel.config.js" a babel.config.cjs"

Me funcionó me estaba volviendo loca con este error. Me fallaban las pruebas.

Muchas gracias

@JuniorCalva40
Copy link

En el error de la configuración de jest, le solucione cambiando el babel.config.js a "babel.config.json", me quedó de la siguiente manera: { "presets": [ [ "@babel/preset-env", { "targets": { "esmodules": true } } ], [ "@babel/preset-react", { "runtime": "automatic" } ] ] } Al hacer este cambio, y cambiar en el jest.config.js a: export default { testEnvironment: 'jest-environment-jsdom', setupFiles: ['./jest.setup.js'] } Ya funciona normalmente, con las configuraciones que Fernando establece al inicio

Gracias me funcionó

@PieroJacinto
Copy link

si les tira error, solo tienen quye renommbrar el archivo jest.config.js a jest.config.cjs, solo cambiando la extension lo arregla.

@JulianLlanten8
Copy link

JulianLlanten8 commented Jun 24, 2023

aplique todas las intalaciones siguiendo los pasos y no se porque no me funciona, El profesor deberia de usar otra libreria de test como vites.

@almendev
Copy link

almendev commented Jul 7, 2023

Creo que en la lista de instalaciones hay que agregar @babel/core

@OscarFriasZavalza
Copy link

si les aparece un error como este "ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' ", tiene que ambiar el archivo yest.config.js a yest.config.cjs

@Nimrockdev
Copy link

Gracias!!

@movarich
Copy link

image
SOLUCIÖN
image

@ramanugan
Copy link

Thanks! :)

A algunos nos aparece un error de este tipo

image

hay que re nombrar los tres archivos con terminacion .cjs

y todo andara bien después:

image

@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

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