Skip to content

Instantly share code, notes, and snippets.

@Kreator-97
Forked from Klerith/vite-testing-config.md
Last active November 25, 2022 00:26
Show Gist options
  • Save Kreator-97/3cc50b09ac365bf44afc49818773b4cc to your computer and use it in GitHub Desktop.
Save Kreator-97/3cc50b09ac365bf44afc49818773b4cc 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
  1. Errors when imports css files

The error: SyntaxError: Invalid or unexpected token when Jest parses CSS files: True, the error is due to Jest trying to parse the CSS as JavaScript, which wont work. So the updated way to handle this is 3 steps, per the Jest documentation on handling static assets, but you dont need to add an additional package like identity-obj-proxy as @chitra suggested unless you're using CSS Modules. And to contrast @james-hibbard 's suggestions: the fileMock.js now looks slightly different and you don't need to create a jest.config.js .

1 in your package.json add this

{ "jest": { "moduleNameMapper": { "\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "/mocks/fileMock.js", "\.(css|less)$": "/mocks/styleMock.js" } } }

2 Then create the following two files:

// mocks/styleMock.js

module.exports = {};

3

// mocks/fileMock.js

module.exports = 'test-file-stub';

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