内部包含功能组件的功能组件 - 测试

Functional component that includes a functional component inside it - Test

我有一个功能组件,我想开玩笑地编写测试。但我无法评估结果。我应该如何为这样的组件编写测试? 这是我要测试的组件:

import React from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import ExpenseForm from "./ExpenseForm";
import { addExpense } from "../store/expenses/actions";

const AddExpensePage = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  function onSubmit(expense) {
    dispatch(addExpense(expense));
    navigate("/");
  }

  return (
    <div>
      <h1>Add Expense</h1>
      <ExpenseForm onSubmit={onSubmit} />
    </div>
  );
};

export default AddExpensePage;

我写了这个测试:

import React from "react";
import * as reactRedux from "react-redux";
import { shallow } from "enzyme";
import AddExpensePage from "../AddExpensePage";
import expenses from "../../fixtures/expenses";

// Mock useDispatch hook
const useDispatch = jest.spyOn(reactRedux, "useDispatch");

jest.mock("react-redux", () => ({
  ...jest.requireActual("react-redux"),
  useDispatch: jest.fn(),
}));

const mockedUsedNavigate = jest.fn();

jest.mock("react-router-dom", () => ({
  ...jest.requireActual("react-router-dom"),
  useNavigate: () => mockedUsedNavigate,
}));

beforeEach(() => {
  useDispatch.mockClear();
});

test("should render AddExpensePage correctly", () => {
  const wrapper = shallow(<AddExpensePage />);
  expect(wrapper).toMatchSnapshot();
});

test("should handle onSubmit", () => {
  const dispatch = jest.fn();
  useDispatch.mockReturnValue(dispatch);
  const onSubmitSpy = jest.fn();
  const wrapper = shallow(<AddExpensePage onSubmit={onSubmitSpy} />);
  wrapper.find("ExpenseForm").prop("onSubmit")(expenses[1]);
  expect(dispatch).toHaveBeenCalled();
  expect(mockedUsedNavigate).toHaveBeenLastCalledWith("/");
  // expect(onSubmitSpy).toHaveBeenLastCalledWith(expenses[1]);
});

我不确定这条线是否有效 "wrapper.find("ExpenseForm").prop("onSubmit")(expenses[1]);"

我也想测试这个“expect(onSubmitSpy).toHaveBeenLastCalledWith(expenses[1]);”。但我找不到如何做到这一点。

你有什么想法可以帮助我吗?

请指教我应该如何编写测试这些组件。

提前致谢。

建议测试组件的行为,而不是它们的实现。因此,不是以编程方式调用您的函数,您应该找到调用它的按钮并模拟点击。与接受测试函数处理的数据的文本输入(我想)相同。

此外,如果您的组件不接受这样的 prop,您不能通过将函数作为 prop 传递来简单地模拟函数。

test("should handle onSubmit", () => {
  const dispatch = jest.fn();
  const navigate = jest.fn();
  useDispatch.mockReturnValue(dispatch);
  useNavigate.mockReturnValue(navigate);

  const wrapper = shallow(<AddExpensePage />);
  const submitBtn = wrapper.find('button[type="submit"]');
  submitBtn.simulate('change', { target: { value: 'myMock' } } );
  
  expect(dispatch).toHaveBeenCalled();
  expect(navigate).toHaveBeenCalledWith("/");
});