Setting up Jest and React Testing Library with Vite Typescript – Aula 46

Posted by

Configuring Jest + React Testing Library in Vite Typescript

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.

0 0 votes
Article Rating
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@oseiascosta1
11 months ago

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

@mateuslopes1831
11 months ago

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?

@jguigo
11 months ago

Você é um anjo!

@CortesDoSans
11 months ago

cara to amanha toda tentando fzr esse jest funcionar vlwwww

@isaquesantos7243
11 months ago

Muito bom os ensinamentos!