You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

1 D铆as
1 Hrs
41 Min
12 Seg
Curso de React Testing Library

Curso de React Testing Library

Wilmer Javier Garzon Cabezas

Wilmer Javier Garzon Cabezas

Testing de Gesti贸n de Datos con Mocks

10/20
Resources

How to organize the testing for the dashboard of our application?

Welcome to a session where we will explore how to ensure the quality of our application through tests on the dashboard, the core where all the magic of orders is displayed! Testing our functionalities is crucial to deliver a robust product. In this session, we will use a simulated environment to help us validate that our orders are displayed correctly.

How do we verify the display of orders on the dashboard?

To start, make sure you have your test environment set up correctly. The first step is to familiarize ourselves with the package.json, which details how our simulated backend runs on port 3001. There, a db.json file contains an array of commands that we must simulate, also known as "mocking".

Creation and structure of the tests

  1. Creation of the test file:
    • Inside src/containers/orders, we create a new file named orders.test.tsx.
  2. Basic test structure:
    • We use the classic describe, it, and expect pattern to organize our test cases.
    • We import the necessary functions from vitest and testing-library/react such as render and screen.
import { render, screen } from '@testing-library/react';import { MemoryRouter } from 'react-router-dom';import Orders from './Orders';
// Our test suitedescribe('Orders Component', () => { it('should show orders', () => { // Test logic will be implemented here });});

How do we perform the necessary 'mocking' for the components?

Import and initial configuration:

  • We import the Orders component and other functions relevant to testing.
  • We implement MemoryRouter and SessionProvider to simulate the structure of our application.

Additional configuration:

  • We create a function called handleRenderOrders that will use render to assemble our component.
  • We import vi to create the necessary function mocks like getOrders.
const handleRenderOrders = () => { render( <MemoryRouter> <SessionProvider> <Orders/> </SessionProvider> </MemoryRouter> );};

How do we achieve effective 'mocking' for data?

To test effectively, we need to ensure that the correct data is being used in each test.

  1. Mock order data (mock orders):
    • We create a constant mockOrders and assign an array of mock orders to it.
const mockOrders = [ { id: 1, product: 'Example product', quantity: 2, },];
  1. Mock session functions:
    • We mock the useSession function to simulate that a user is already logged in.
vi.mock('path/to/auth/context', () => ({. ..jest.requireActual('path/to/auth/context'), useSession: jest.fn().mockReturnValue({ user: { role: 'Visualizer' }, }),}),}));

How do we perform render validation?

With all the structure and mocks ready, it's time to check that everything is working correctly.

  • Validating that the orders are rendered: We use getAllByRole to get all the orders in the component, making sure that their length matches that of mockOrders.
const orders = screen.getAllByRole('heading', { level: 3 });expect(orders).toHaveLength(mockOrders.length);

And there you have it! You have mastered the ability to perform effective tests in a simulated environment, ensuring that the orders on our dashboard are displayed as they should be. This knowledge is essential to maintain the integrity of the application as it evolves. Keep practicing and you'll see your testing skills become more and more solid!

Contributions 3

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Me han encantado las clases el profe le pone mucho empe帽o y es muy divertido saludos desde Cuba
Es muy interesante ver c贸mo se puede evaluar el comportamiento de una aplicaci贸n tan a detalle. Un gran curso, y el profe Wilmer lo hace muy ameno.
As铆 me quedo el test```js it("deberia redirigir a /orders", async () => { mockGetAuth.mockResolvedValue({ success: true }); loginRender(); const usernameInput = screen.getByPlaceholderText("Username"); const passwordInput = screen.getByPlaceholderText("Password"); const buttonLogin = screen.getByRole("button", { name: "Login" }); await act(() => { fireEvent.change(usernameInput, { target: { value: "correctUser" } }); fireEvent.change(passwordInput, { target: { value: "correctPassword" } }); fireEvent.click(buttonLogin); }); await waitFor(() => { expect(mockGetAuth).toHaveBeenCalledWith( "correctUser", "correctPassword" ); expect(mockNavegate).toHaveBeenCalledWith("/orders"); }); }); it("deberia mostrar la contrase帽a cuando oprimo show, y se debria ocultar cuando oprimo hide", async () => { loginRender(); const passwordInput = screen.getByPlaceholderText("Password"); const buttonTogglePassword = screen.getByRole("button", { name: "show", }); await act(() => { fireEvent.click(buttonTogglePassword); }); expect(passwordInput).toHaveAttribute("type", "text"); expect(buttonTogglePassword).toHaveTextContent("hide"); await act(() => { fireEvent.click(buttonTogglePassword); }); expect(passwordInput).toHaveAttribute("type", "password"); expect(buttonTogglePassword).toHaveTextContent("show"); }); ```