【问题标题】:Mocking useHistory and expect toBeCalledWith模拟 useHistory 并期望 toBeCalledWith
【发布时间】:2020-05-10 00:56:21
【问题描述】:

我不想检查在我的测试中是否使用正确的参数调用了history.push()。 我不确定模拟useHistory()的正确方法是什么

我尝试了this 解决方案。但似乎无法检查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');
});

有什么方法可以确保 history.push() 已使用正确的参数调用?

【问题讨论】:

    标签: reactjs jestjs react-hooks react-testing-library


    【解决方案1】:

    试试这个,将模拟的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");
    });
    
    

    【讨论】:

    • 无法访问 jest.mock 中的 mockHistoryPush
    猜你喜欢
    • 2020-10-01
    • 2023-03-14
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多