Skip to content

Instantly share code, notes, and snippets.

@Klerith
Last active June 26, 2024 12:49
Show Gist options
  • Save Klerith/b2eafa2a5fb9f09d6d043781be976e06 to your computer and use it in GitHub Desktop.
Save Klerith/b2eafa2a5fb9f09d6d043781be976e06 to your computer and use it in GitHub Desktop.
Vite + Testing + Jest - Completo

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. Para componentes que importen CSS, crear un archivo llamado: tests/mocks/styleMock.js
module.exports = {};
  1. Opcional, pero eventualmente necesario, crear Jest config y setup:

jest.config.js

module.exports = {
    testEnvironment: 'jest-environment-jsdom',
    setupFiles: ['./jest.setup.js'],
    transformIgnorePatterns: [],
    
    // ModuleNameMapper sólo si ocupamos importar CSS en nuestros componentes para el testing
    moduleNameMapper: {
        '\\.(css|less)$': '<rootDir>/tests/mocks/styleMock.js',
    },
}

jest.setup.js

// En caso de necesitar la implementación del FetchAPI
// yarn add -D whatwg-fetch
// import 'whatwg-fetch'; 

// En caso de encontrar paquetes que lo requieran 
// yarn add -D setimmediate
// import 'setimmediate';

// En caso de tener variables de entorno y aún no soporta el import.meta.env
// yarn add -D dotenv
// require('dotenv').config({
//     path: '.env.test'
// });

// Realizar el mock completo de las variables de entorno
// jest.mock('./src/helpers/getEnvVariables', () => ({
//     getEnvVariables: () => ({ ...process.env })
// }));
@JesusMurF
Copy link

Hola Fernando, personalmente he tenido que añadir la propiedad "transform" en el jest.config.js porque sino no me funcionaba correctamente, lo dejo aquí por si a alguien le ayuda:

module.exports = { ... transform: { '\\.[jt]sx?$': 'babel-jest', }, ... };

@luciaaldana
Copy link

Hola Fernando! Muchas gracias por este gist 😄 Yo le configuré ESLint al proyecto. Así que tuve que agregar esto para que no me de errores las configuraciones de jest y babel:

  env: {
    jest: true,
    node: true,
  }

@cr-arostegui
Copy link

I was getting the following error when running "npm run test":

ReferenceError: module is not defined in ES module scope This file is being treated as an ES module because it has a '.js' file extension and '/Users/..../calendar/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

To solve this issue I replaced the code below in the jest.config.js file:
module.exports = {
by
export default {

@oscar-soto
Copy link

nevertheless, you can change the extension .js to cjs, it's working too

@paulespinozarl
Copy link

Pude continuar por la solución de ''cr-arostegui'', no me andaba el test. GRACIAS!

@AlejoDevLov
Copy link

Gracias. finalmente me pudo correr el jest, aunque me tocó hacer una configuracion adicional y fue que el archico jest.config.js, me tocó cambiarle la extension por 'cjs'

@josuecaceres
Copy link

Muchas gracias me ha encantado el curso de react.

@Jesus2PQ
Copy link

Muchas Gracias Fernando, por tanto profesionalismo y tu increíble pedagogía durante el curso...!

@mrGio19
Copy link

mrGio19 commented Apr 13, 2024

Me arroja este error, alguien sabe cómo solucionarlo?:

tests/heroes/pages/SearchPage.test.jsx
● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

.
.
.
SyntaxError: Cannot use import statement outside a module

  1 | import { useLocation, useNavigate } from 'react-router-dom';
  2 | // Primero se instalo en la consola con npm install query-string
> 3 | import queryString from 'query-string';
    | ^
  4 |
  5 | import { useForm } from '../../hooks/useForm';
  6 | import { HeroCard } from '../components';

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
  at Object.require (src/heroes/pages/SearchPage.jsx:3:1)
  at Object.require (src/heroes/pages/index.js:5:1)
  at Object.require (src/heroes/index.js:3:1)
  at Object.require (tests/heroes/pages/SearchPage.test.jsx:4:1)

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