Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

671
Views
¿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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!