Skip to content

Instantly share code, notes, and snippets.

@AlexAlonsoMontero
Forked from Klerith/vite-testing-config.md
Last active October 9, 2023 01:54
Show Gist options
  • Save AlexAlonsoMontero/981815de517902322f7a1c6b7bae9baf to your computer and use it in GitHub Desktop.
Save AlexAlonsoMontero/981815de517902322f7a1c6b7bae9baf 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
npm install --dev jest babel-jest @babel/preset-env @babel/preset-react 
npm install --dev @testing-library/react @types/jest jest-environment-jsdom
  1. Opcional: Si usamos Fetch API en el proyecto:
yarn add --dev whatwg-fetch
npm install --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' } ],
    ],
};
  • 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
import 'whatwg-fetch'; // <-- yarn add whatwg-fetch
import 'setimmediate';

  1. Variables de entorno:
  • Creamos un fichero, yo lo creo en una carpeta helpers con el siguiente código. (Nombre del fichero getEnviroments.js)

getEnviroments.js

export const getEnviroments = () =>{
    import.meta.env;
    return {
        ...import.meta.env
    }
}
  • En el fichero jest.setup.js ( es posible que sea necesario instalar dotenv )

jest.setup.js

//ponemos el path en el que se situan las variables de entorno
require('dotenv').config({
    path: '.env'
})
//Creamos un mock con todas las variables de entorno
jest.mock('./src/helpers/getEnviroments',()=>({
    getEnviroments: () => ({...process.env})
}))
  • Ya podemos usar en los ficheros test process.env
@epsilon11101
Copy link

muchas gracias me sirvio para los env ,

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