首页 > 解决方案 > Jest.fn() 调用了 0 次,应该调用一次。(检查其他问题)

问题描述

我已经检查了有关此主题的其他一些问题,但是对于我的一生来说,无法弄清楚是什么导致这个模拟函数不被调用。下面我提供了所有我认为相关的代码,但请随时询问我是否需要包含更多代码。

我们使用 React-Hook-Forms。

每个之前:

  beforeEach(async () => {
    jest.clearAllMocks();
    await act(async () => {
      history = createMemoryHistory({
        initialEntries: ["/admin/615"]
      });
      container = renderWithRouter(
        <Admin
          setCollections={mockSetCollections}
          setCourses={mockSetCourses}
          data={mockData}
          isAdmin={true}
          azureOid={1}
        />,
        "/admin/:id",
        history,
        "/courses"
      );
    });
  });

测试:

test("Admin page calls mockSetCourses when submit button is clicked for Editing a Course", async () => {
  await act(async () => {
    userEvent.click(screen.getByTestId("adminSubmitButton"));
  });
  expect(mockSetCourses).toHaveBeenCalledTimes(1);
});

提交时:

const onSubmit = data => {
    console.log(data)
    let formData = getFormattedFormData(data);
    let collectionsDuplicates = getCollectionsDuplicates();

    let descriptionError =
      formData.description === "" || formData.description === "<p><br></p>";

    if (collectionsDuplicates.length > 0 && descriptionError) {
      setErrorMessage({ collection: true, description: true });
    } else if (collectionsDuplicates.length > 0 && !descriptionError) {
      setErrorMessage({ collection: true, description: false });
    } else if (!collectionsDuplicates.length > 0 && descriptionError) {
      setErrorMessage({ collection: false, description: true });
    } else {
      setErrorMessage({ collection: false, description: false });

      if (id) {
        editCourse(id, formData, setRedirect, setCourses, setCollections);
      } else {
        addCourse(formData, setRedirect, azureOid, setCourses, setCollections);
      }
    }
  };

我已检查是否单击了正确的按钮,并且确实如此。

编辑:使用该功能的请求:

export const editCourse = (
  id,
  formData,
  setRedirect,
  setCourses,
  setCollections
) => {
  sendRequest(
    "patch",
    `courses/${id}`,
    () => {
      getCourses(setCourses);
      getCollections(setCollections);
      setRedirect(`/courses/${id}`);
    },
    formData
  );
};

标签: javascriptreactjsunit-testingtestingjestjs

解决方案


推荐阅读