Configuring Jest + React Testing Library in Vite Typescript
In this tutorial, we will learn how to configure Jest and React Testing Library in a Vite Typescript project to write tests for our React components.
Setting Up Jest
First, let’s install the necessary packages for Jest:
npm install --save-dev jest @types/jest ts-jest
Next, we need to create a jest.config.js
file in the root of our project with the following configuration:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
};
Setting Up React Testing Library
We also need to install React Testing Library:
npm install --save-dev @testing-library/react @testing-library/jest-dom
Then, we can create a setupTests.ts
file in the src
folder with the following content:
import '@testing-library/jest-dom/extend-expect';
Configuring Vite to work with Jest
Finally, we need to modify our package.json
file to add a test script that runs Jest. We can also add a test:watch script to run Jest in watch mode:
"scripts": {
"test": "jest",
"test:watch": "jest --watchAll"
}
Writing Our First Test
Now that we have everything set up, we can write our first test for a React component using Jest and React Testing Library. Here’s an example test for a simple component:
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';
test('renders the component', () => {
render();
const component = screen.getByText('Hello, World!');
expect(component).toBeInTheDocument();
});
With these steps, we have successfully configured Jest and React Testing Library in our Vite Typescript project. Now we can start writing tests for our React components to ensure they work as expected.
Não consegui sair desse erro:
You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously.
pesquisei um monte e nada
Tive só que mudar o config do babel de .js pra .cjs mas funcionou. Que luta que foi pra eu achar isso, muito obrigado mesmo. Aliás, teria alguma outra lib de teste ou coisa semelhante que não precise de tanta configuração assim?
Você é um anjo!
cara to amanha toda tentando fzr esse jest funcionar vlwwww
Muito bom os ensinamentos!