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:

0 D铆as
3 Hrs
47 Min
54 Seg
Curso de React Testing Library

Curso de React Testing Library

Wilmer Javier Garzon Cabezas

Wilmer Javier Garzon Cabezas

Testing a un Proceso de Autenticaci贸n (Parte 2)

9/20
Resources

How to perform successful login testing?

When creating applications, testing the authentication flow is crucial to ensure security and functionality. In this case, we will see how to implement a test for a successful login using the right tools in a React environment.

What do we need for a successful login test?

First, we need to make sure that our login redirects us correctly when we use the correct credentials. In our Platzi Orders application, we want a valid login to navigate to /orders.

  1. Component Rendering:

    • Using SessionProvider and MemoryRouter.
    • Creation of a reusable function called handleLogin to avoid repetitive code.
    const handleLogin = () => { return render( <MemoryRouter> <SessionProvider> <Login/> </SessionProvider> </MemoryRouter> );};
  2. Test Structure:

    • Creating the test case that redirects to /orders.
    • Use of mock for getAuth promise.

    In the test file, we set up the mock and use the following method:

    mockGetAuth.mockResolvedValue({ success: true,});
  3. Navigation Mocking:

    • Mock from the React Router DOM module to mock the navigate function.
    const mockNavigate = jest.fn();jest.mock('react-router-dom', () => ({. ..jest.requireActual('react-router-dom'), useNavigate: () => mockNavigate,}));
  4. Interactions and Assertions:

    • Interaction with text input elements to simulate a login.
    • Use of waitFor to handle asynchronous operations.
    await waitFor(() => { expect(mockNavigate).toHaveBeenCalledWith('/orders');});

How to make sure the tests are working?

It is important to verify that our tests are actually evaluating the expected scenarios. By changing the expected values in our assertions and seeing that the test fails, we can make sure that they are correctly configured.

  1. Verify navigation:

    • Changing the expected route in toHaveBeenCalledWith('/orders') to another such as '/incorrectRoute' should force a failure, demonstrating that the test is effective.
  2. Correct errors:

    • Code review to correct typos and syntax errors that could cause tests to fail for incorrect reasons.

How to incorporate new functionality into the test?

When developing an application, it is possible to integrate additional functionality to improve the user experience. For example, in our use case, adding a test for the Show button on the login form would enrich our tests.

Challenge:Create a new use case that verifies the Show button toggles password visibility. This will allow you to practice creating more complex scenarios and manage variability in interface components.

In summary, performing thorough and well-configured tests on our application ensures that all functionalities, including authentication, work correctly and securely. Keep learning and improving your testing skills!

Contributions 5

Questions 0

Sort by:

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

Otra forma de que se renderice el componente antes de que se corra cada test podria ser con beforeEach y no ahorramos tener que llamar la funcion en cada it. ```js describe('<Login />', () => { beforeEach(() => { render( <SessionProvider> <MemoryRouter> <Login /> </MemoryRouter> </SessionProvider> ) }) ```describe('\<Login />', () => {聽 beforeEach(() => {聽 聽 render(聽 聽 聽 \<SessionProvider>聽 聽 聽 聽 \<MemoryRouter>聽 聽 聽 聽 聽 \<Login />聽 聽 聽 聽 \</MemoryRouter>聽 聽 聽 \</SessionProvider>聽 聽 )聽 })
El reto de probar si es password o text al hacer click en el bot贸n show, seria algo as铆 ```js it('should show password', async () => { handleLogin(); const passwordInput = screen.getByPlaceholderText("Password"); const buttonTogglePassword = screen.getByRole("button", { name: "show" }); await act(() => { fireEvent.click(buttonTogglePassword); }); expect(passwordInput).toHaveAttribute("type", "text"); await act(() => { fireEvent.click(buttonTogglePassword); }); expect(passwordInput).toHaveAttribute("type", "password"); } ); ```it('should show password', async () => { handleLogin(); const passwordInput = screen.getByPlaceholderText("Password"); const buttonTogglePassword = screen.getByRole("button", { name: "show" }); await act(() => { fireEvent.click(buttonTogglePassword); }); expect(passwordInput).toHaveAttribute("type", "text"); await act(() => { fireEvent.click(buttonTogglePassword); }); expect(passwordInput).toHaveAttribute("type", "password"); } );
No se si el codigo de mi test es demasiado simple, pero me funciono 馃榿.聽 it("deberia de cambiar el texto de show a hide y viceversa", async () => {聽 聽 renderLogin() 聽 聽 const button = screen.getByText("show")聽 聽 expect(button).toBeInTheDocument()聽 聽 await act(() => \[聽 聽 聽 fireEvent.click(button)聽 聽 ])聽 聽 const toggleButton = screen.getByText("hide")聽 聽 expect(toggleButton).toBeInTheDocument()聽 })}) ```js it("deberia de cambiar el texto de show a hide y viceversa", async () => { renderLogin() // Primero valido que si este el boton con el texto show const button = screen.getByText("show") expect(button).toBeInTheDocument() // Luego hago la simulacion del click await act(() => [ fireEvent.click(button) ]) // Valido si el texto tiene el nuevo texto deseasdo "hide" const toggleButton = screen.getByText("hide") expect(toggleButton).toBeInTheDocument() }) ```
Validando en el caso de prueba que cambie tanto el type del input password y que cambie el texto del bot贸n de "show" a "hide" y viceversa ![](https://static.platzi.com/media/user_upload/image-e5251f10-41bd-4aa7-807c-c7c95da2a711.jpg)
Hice el reto, pero me surgi贸 un pregunta, 驴es v谩lido colocar un expect entre medio y no al final como lo venimos haciendo en el curso? Ya que hice un expect que verifique que el tipo de input es password antes de gatillar el evento click para que lo transforme en tipo texto ```js it("should input type change when you show the password", async () => { handleLogin(); const passwordInput = screen.getByPlaceholderText("Password"); const buttonTogglePassword = screen.getByText("show"); expect(passwordInput.getAttribute("type")).toBe("password"); await act(() => { fireEvent.change(passwordInput, { target: { value: "securePassword" } }); fireEvent.click(buttonTogglePassword); }); expect(passwordInput.getAttribute("type")).toBe("text"); }); ``` expect(passwordInput.getAttribute("type")).toBe("password"); await act(() => { fireEvent.change(passwordInput, { target: { value: "securePassword" } }); fireEvent.click(buttonTogglePassword); }); expect(passwordInput.getAttribute("type")).toBe("text"); });