Дразнить использовать Историю и ожидать BeCalledWith - PullRequest
0 голосов
/ 23 января 2020

Я не хочу проверять, был ли вызван history.push() с правильными параметрами в моем тесте. Я не уверен, как правильно издеваться useHistory()

Я пытался это решение. Но, похоже, я не могу проверить, был ли вызван push().

App.tsx

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

const App: React.FC = () => {
    const history = useHistory();
    const onClick = () => {
        history.push('/anotherPath');
    };
    return (
        <div>
            <button onClick={onClick}>click</button>
        </div>
    );
};

export default App;

App.test.tsx

import React from 'react';
import {render, fireEvent} from '@testing-library/react';
import App from './App';
import {useHistory} from 'react-router-dom'

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

test('renders learn react link', async () => {
    const app = render(<App/>);
    fireEvent.click(app.getByText('click'));
    expect(useHistory().push).toBeCalledWith('/anotherPath');
});

Is Есть ли способ убедиться, что history.push() был вызван с правильными параметрами?

1 Ответ

0 голосов
/ 23 января 2020

Попробуйте, присвойте смоделированный метод push в переменную и используйте его для подтверждения, вызывается ли он с правильными параметрами.

import React from "react";
import { render, fireEvent } from "@testing-library/react";

import { useHistory } from "react-router-dom";
const mockHistoryPush = jest.fn();

const App: React.FC = () => {
  const history = useHistory();
  const onClick = () => {
    history.push("/anotherPath");
  };
  return (
    <div>
      <button onClick={onClick}>click</button>
    </div>
  );
};
jest.mock("react-router-dom", () => ({
  useHistory: () => ({
    push: mockHistoryPush
  })
}));

test("renders learn react link", async () => {
  const { getByText } = render(<App />);
  fireEvent.click(getByText("click"));
  expect(mockHistoryPush).toBeCalledWith("/anotherPath");
});

...