Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save vqc1909a/f1f3ec3aa88c912e655f39d5c5c1416c to your computer and use it in GitHub Desktop.

Select an option

Save vqc1909a/f1f3ec3aa88c912e655f39d5c5c1416c to your computer and use it in GitHub Desktop.
Setup vite react project with javascript

Instalación y configuracion de Jest + React Testing Library

En proyectos de React + Vite

  1. Instalaciones:

    yarn add -D @babel/core @babel/preset-env @babel/preset-react jest babel-jest react-test-renderer @types/jest @testing-library/react @testing-library/dom @testing-library/jest-dom @testing-library/user-event jest-environment-jsdom
  2. Opcional: Si usamos Fetch API en el proyecto:

    yarn add -D whatwg-fetch
  3. Actualizar los scripts del package.json

    "scripts: {
    .
    .
    .
    "test": "jest --watchAll"
    }
  4. Crear la configuración de babel babel.config.js or babel.config.cjs

    //babel.config.js
    export default {
        presets: [
            ['@babel/preset-env', {targets: {esmodules: true, node: 'current'}}],
            ['@babel/preset-react', {runtime: 'automatic'}],
        ],
    };

    Or

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

    NOTE: Renaming babel.config.js to babel.config.cjs to explicitly indicate that it is a CommonJS module.

  5. Opcional, pero si vas a trabajar con syntaxis del DOM de react, crear Jest config y setup:

    jest.config.js

    export default {
        testEnvironment: 'jest-environment-jsdom',
        
        //this line works to make a global configuration before run the tests
        setupFiles: ['./jest.setup.js']
    }

    jest.setup.js

    //If will install the polyfill Fetch API, to will need to import this package
    import 'whatwg-fetch';
     //For avoid some mistakes jest DOM syntax in file tests
    import '@testing-library/jest-dom'
  6. And you will be ready for your firt test case

        import { render } from "@testing-library/react";
        import { FirstApp } from "../src/FirstApp";
    
        describe('Pruebas en <FirstApp />', () => {
            test('debe de hacer match con el snapshot', () => {
    
            const title = "Hola, soy Goku"
            const {container} = render(<FirstApp title={title} subTitle={"Hola, Soy el subtitulo"} />)
            expect(container).toMatchSnapshot();
        })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment