¿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.
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(), }), }));
Este funcionó para mí:
jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useHistory: () => ({ push: jest.fn() }) }));
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'); });