Soy nuevo en las pruebas con broma y quiero probar el siguiente código.
import React from "react"; import "./ButtonLogin.css"; import { Link } from 'react-router-dom'; function ButtonLogin() { return ( <Link to="/login"> <button className="button-login">Iniciar sesión</button></Link> ) } export default ButtonLogin; import { MemoryRouter } from 'react-router-dom'; import { render, fireEvent, Link } from '@testing-library/react'; import { ButtonLogin } from './ButtonLogin'; it('routes to a new route', async () => { ButtonLogin = jest.fn(); const { getByText } = render( <MemoryRouter ButtonLogin={ButtonLogin}> <Link to="/login">Iniciar sesión</Link> </MemoryRouter> ); fireEvent.click(getByText('Iniciar sesión')); expect(ButtonLogin).toHaveBeenCalledWith('/login'); });He realizado la siguiente prueba pero falla y me sale el siguiente error en la linea 9. rutas a una nueva ruta
"ButtonLogin" is read-only.Puede usar la función createMemoryHistory y el componente Router para probarlo. Cree un historial de memoria con entradas iniciales para simular la ubicación actual, de esta manera no confiamos en el entorno real del navegador. Después de activar el evento de clic, afirme que el nombre de la pathname se cambió correctamente o no.
ButtonLogin.tsx :
import React from 'react'; import { Link } from 'react-router-dom'; function ButtonLogin() { return ( <Link to="/login"> <button className="button-login">Iniciar sesión</button> </Link> ); } export default ButtonLogin; ButtonLogin.test.tsx :
import { fireEvent, render } from '@testing-library/react'; import React from 'react'; import { Router } from 'react-router-dom'; import ButtonLogin from './ButtonLogin'; import { createMemoryHistory } from 'history'; describe('ButtonLogin', () => { test('should pass', () => { const history = createMemoryHistory({ initialEntries: ['/home'] }); const { getByText } = render( <Router history={history}> <ButtonLogin /> </Router> ); expect(history.location.pathname).toBe('/home'); fireEvent.click(getByText('Iniciar sesión')); expect(history.location.pathname).toBe('/login'); }); });resultado de la prueba:
PASS examples/69878146/ButtonLogin.test.tsx (10.675 s) ButtonLogin ✓ should pass (41 ms) -----------------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s -----------------|---------|----------|---------|---------|------------------- All files | 100 | 100 | 100 | 100 | ButtonLogin.tsx | 100 | 100 | 100 | 100 | -----------------|---------|----------|---------|---------|------------------- Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 11.722 s, estimated 12 s versión del paquete: "react-router-dom": "^5.2.0"