Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

674
Vistas
¿Cómo burlarse del gancho useHistory en broma?

¿Estoy usando el gancho UseHistory en el enrutador de reacción v5.1.2 con mecanografiado? Al ejecutar la prueba unitaria, tengo un problema.

TypeError: no se puede leer la propiedad 'historial' de undefined.

 import { mount } from 'enzyme'; import React from 'react'; import {Action} from 'history'; import * as router from 'react-router'; import { QuestionContainer } from './QuestionsContainer'; describe('My questions container', () => { beforeEach(() => { const historyHistory= { replace: jest.fn(), length: 0, location: { pathname: '', search: '', state: '', hash: '' }, action: 'REPLACE' as Action, push: jest.fn(), go: jest.fn(), goBack: jest.fn(), goForward: jest.fn(), block: jest.fn(), listen: jest.fn(), createHref: jest.fn() };//fake object jest.spyOn(router, 'useHistory').mockImplementation(() =>historyHistory);// try to mock hook }); test('should match with snapshot', () => { const tree = mount(<QuestionContainer />); expect(tree).toMatchSnapshot(); }); });

También he intentado usar jest.mock('react-router', () =>({ useHistory: jest.fn() })); Pero todavía no funciona.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Necesitaba lo mismo al reducir un componente funcional de reacción que usa useHistory .

Resuelto con el siguiente simulacro en mi archivo de prueba:

 jest.mock('react-router-dom', () => ({ useHistory: () => ({ push: jest.fn(), }), }));
over 4 years ago · Santiago Trujillo Denunciar

0

Este funcionó para mí:

 jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useHistory: () => ({ push: jest.fn() }) }));
over 4 years ago · Santiago Trujillo Denunciar

0

Aquí hay un ejemplo más detallado, tomado del código de prueba de trabajo (ya que tuve dificultades para implementar el código anterior):

Componente.js

 import { useHistory } from 'react-router-dom'; ... const Component = () => { ... const history = useHistory(); ... return ( <> <a className="selector" onClick={() => history.push('/whatever')}>Click me</a> ... </> ) });

Componente.prueba.js

 import { Router } from 'react-router-dom'; import { act } from '@testing-library/react-hooks'; import { mount } from 'enzyme'; import Component from './Component'; it('...', () => { const historyMock = { push: jest.fn(), location: {}, listen: jest.fn() }; ... const wrapper = mount( <Router history={historyMock}> <Component isLoading={false} /> </Router>, ).find('.selector').at(1); const { onClick } = wrapper.props(); act(() => { onClick(); }); expect(historyMock.push.mock.calls[0][0]).toEqual('/whatever'); });
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda