es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Cómo probar un cambio de URL con en React Router DOM.

Quiero probar, cuando se hace clic en el botón ‘Restablecer filtros’, ir a /offerings, pero no sé cómo probar este componente <Link /> de react-router-dom.

Botón

<Link to="/offerings">
   <StyledButton trackingId="reset-filters">Restablecer filtros</StyledButton>
</Link>

Archivo de prueba:

it('debería ir a /offerings cuando se hace clic en el botón después de iniciar sesión', () => {
    const wrapper = mountWithTheme(
      <Provider
        store={configureMockStore({
          user: {
            userState: {
              loggedIn: true,
            },
          },
        })}
      >
        <BrowserRouter>
          <MarketplaceEmptyState resetFilter={resetFilter} />
        </BrowserRouter>
      </Provider>
    );

    wrapper.find('MarketplaceEmptyState').setState({
      allStatusFetched: true,
    });

    expect(
      wrapper
        .find('[data-cy="empty-state-filter-copy"]')
        .first()
        .text()
    ).toEqual(`Por favor, restablezca los filtros.`);

    wrapper.find('button[id="reset-filters"]').simulate('click');

    const leftClick = {button: 0} << -----------------------------|
    userEvent.click(screen.getByText(/ofertas/i), leftClick) << ------  Intenté esto pero no funciona
  });
Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Para probar el componente <link> de react-router-dom, se puede usar el componente MemoryRouter de react-router en el archivo de prueba. Reemplace el componente <browserrouter> por <memoryrouter initialentries="{['/']}" initialindex="{0}">. Esto le permitirá simular clics en el componente <link> y comprobar que se dirige a la URL correcta.

    Aquí hay un archivo de prueba actualizado con los cambios:

    import { MemoryRouter } from 'react-router';
    import { Provider } from 'react-redux';
    import configureMockStore from 'redux-mock-store';
    import { mountWithTheme } from '../../../../test-utils';
    import { screen } from '@testing-library/react';
    import userEvent from '@testing-library/user-event';
    import MarketplaceEmptyState from '../MarketplaceEmptyState';
    
    it('debería ir a /offerings cuando se hace clic en el botón al iniciar sesión', () => {
      const resetFilter = jest.fn();
      const wrapper = mountWithTheme(
        <provider store="{configureMockStore({" user:="" {="" userstate:="" {="" loggedin:="" true,="" },="" },="" })}="">
          <memoryrouter initialentries="{['/']}" initialindex="{0}">
            <marketplaceemptystate resetfilter="{resetFilter}"></marketplaceemptystate>
          </memoryrouter>
        </provider>
      );
    
      wrapper.find('MarketplaceEmptyState').setState({
        allStatusFetched: true,
      });
    
      expect(
        wrapper
          .find('[data-cy="empty-state-filter-copy"]')
          .first()
          .text()
      ).toEqual(`Please reset the filters.`);
    
      const leftClick = { button: 0 };
      userEvent.click(screen.getByText(/offerings/i), leftClick);
    
      expect(wrapper.find('MemoryRouter').instance().history.location.pathname).toEqual('/offerings');
    });
    

    En la prueba, se simula un clic en el componente <link> utilizando userEvent.click(screen.getByText(/offerings/i), leftClick), luego se verifica que la URL haya cambiado a /offerings utilizando expect(wrapper.find('MemoryRouter').instance().history.location.pathname).toEqual('/offerings');.

Comments are closed.