Skip to content

Instantly share code, notes, and snippets.

@Klerith
Last active May 1, 2024 22:11
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
@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

@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

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