programing

history hook in jest를 조롱하는 방법?

prostudy 2022. 3. 11. 22:37
반응형

history hook in jest를 조롱하는 방법?

형식 설명과 함께 반응 라우터 v5.1.2에서 UseHistory 후크를 사용하는 중?유닛 테스트를 할 때 문제가 생겼다.

TypeError: 정의되지 않은 속성 'history'를 읽을 수 없음.

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();
    });
});

또한 나는 사용하려고 노력했다.jest.mock('react-router', () =>({ useHistory: jest.fn() }));하지만 여전히 작동하지 않는다.

다음과 같은 기능을 사용하는 반응 기능 구성요소를 얕잡아 볼 때 동일한 기능이 필요했다.useHistory.

내 시험 파일의 다음과 같은 모의고사로 해결했다.

jest.mock('react-router-dom', () => ({
  useHistory: () => ({
    push: jest.fn(),
  }),
}));

이건 내게 효과가 있었어

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useHistory: () => ({
    push: jest.fn()
  })
}));

위의 코드를 구현하는 데 어려움을 겪었기 때문에 작업 테스트 코드에서 가져온 보다 자세한 예제가 여기에 있다.

구성 요소.js

  import { useHistory } from 'react-router-dom';
  ...

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

구성 요소.test.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');
  });

내 정치인 모자를 쓰고 네가 엉뚱한 질문을 하고 있다고 감히 말할 수 있겠구나.

그런거 아냐.useHistory비웃고 싶은 거겠지.대신 당신은 단지 당신이 통제하는 역사 오브젝트로 그것을 먹이고 싶을 것이다.

또한 이 기능을 통해 다음을 확인할 수 있다.push두 개의 상위 답변(이 글을 쓰는 순간)과 마찬가지로 호출.

정말 그렇다면createMemoryHistory뒤를 받으세요:

import {Router} from 'react-router-dom'
import {createMemoryHistory} from 'history'

test('QuestionContainer should handle navigation', () => {
  const history = createMemoryHistory()
  const pushSpy = jest.spyOn(history, 'push') // or 'replace', 'goBack', etc.
  render(
      <Router history={history}>
        <QuestionContainer/>
      </Router>
  )
  userEvent.click(screen.getByRole('button')) // or whatever action relevant to your UI
  expect(pushSpy).toHaveBeenCalled()
})

github react-router repo에서 useHistory hook은 싱글톤 컨텍스트를 사용한다는 것을 발견했는데, MemoryRouter 산에서 사용을 시작했을 때 컨텍스트를 찾아 작업을 시작했다.그러니 고쳐라.

import { MemoryRouter } from 'react-router-dom';
const tree =  mount(<MemoryRouter><QuestionContainer {...props} /> </MemoryRouter>);

사용의 푸시 기능을 조롱하는 방법History:

import reactRouterDom from 'react-router-dom';
jest.mock('react-router-dom');

const pushMock = jest.fn();
reactRouterDom.useHistory = jest.fn().mockReturnValue({push: pushMock});

그런 다음, 함수를 호출했는지 확인하는 방법:

expect(pushMock).toHaveBeenCalledTimes(1);
expect(pushMock).toHaveBeenCalledWith('something');

이것은 나에게 효과가 있다. 나도 useLocation에 문제가 있었다.

jest.mock('react-router-dom', () => ({
  useHistory: () => ({
    push: jest.fn()
  }),
  useLocation: jest.fn().mockReturnValue({
    pathname: '/another-route',
    search: '',
    hash: '',
    state: null,
    key: '5nvxpbdafa'
})}))

나는 위의 답변이 매우 도움이 된다는 것을 알았다.그러나 나는 스파이 능력과 실제 기능성을 시험하는 능력을 놓쳤다.하지만 단순히 모의 함수의 이름을 짓는 것만으로 나는 그것을 먼저 해결했다.

const mockPush = jest.fn();
jest.mock('react-router-dom', () => ({
  useHistory: () => {
    const push = () => mockPush ();
    return { push };
  },
}));

참조URL: https://stackoverflow.com/questions/58392815/how-to-mock-usehistory-hook-in-jest

반응형