Vitest React-Redux 按钮单元测试失败

问题描述 投票:0回答:1

我在使用 Vitest、react-testing-library 和 jest dom 在我的应用程序组件中通过按钮单击测试时遇到问题。我是单元测试的新手,我似乎不知道如何让表单中的提交按钮测试正常工作。 (添加按钮)

我收到断言错误:预期“spy”被调用 1 次,但被调用 0 次

这是我的 TaskForm 组件

import { useDispatch } from "react-redux";
import { add } from "./taskFormSlice";
import { useRef, useState } from "react";
import Tasks from "./Tasks";

const TaskForm = () => {
  const dispatch = useDispatch();
  const task = useRef<string>("");
  // local state to reset input field after submitting form
  const [userInputVal, setUserInputVal] = useState("");

  return (
    <div className="flex flex-col space-y-8 items-center justify-center min-h-screen bg-indigo-900">
      <div className="text-7xl text-white mt-10">To Do App</div>
      <div className="flex flex-row space-y-4 items-center justify-center">
        <form onSubmit={(e) => e.preventDefault()}>
          <input
            value={userInputVal}
            onChange={(e) => {
              setUserInputVal(e.target.value);
              task.current = e.target.value;
            }}
            className=" w-96 border-solid border-sky-500 rounded-full border-2 px-8 py-2 placeholder:text-center text-md"
            placeholder="Enter Task"
          />
          <div className="inline-block">
            <button
              className="px-4 py-2 bg-blue-700 rounded-full text-white shadow-lg hover:shadow-sky-700 ml-40 mt-2 sm:ml-2"
              type="submit"
              onClick={() => {
                setUserInputVal(" ");
                dispatch(add(task.current));
              }}
            >
              Add
            </button>
          </div>
        </form>
      </div>
      <Tasks></Tasks>
    </div>
  );
};

export default TaskForm;

这是我的测试文件的一部分,其中包含添加/提交按钮的单元测试。通过将按钮传递到组件中来模拟按钮单击似乎不是正确的方法,但我不确定如何模拟按钮单击功能以便我可以测试按钮将被单击。

import { describe, expect, test, vi } from "vitest";
import { fireEvent, screen, waitFor } from "@testing-library/react";
import TaskForm from "./TaskForm";

// Unit Test on React components
// Unit test to test that input box takes in a input
describe.sequential("to do list components render correctly", () => {
  test("input box takes in user input", async () => {
    renderWithProviders(<TaskForm></TaskForm>);
    const input = screen.getByPlaceholderText("Enter Task");
    fireEvent.change(input, { target: { value: "test todo" } });
    await waitFor(() => {
      expect(input).toHaveValue("test todo");
    });
  });
  test("Test button click to ensure that it works", () => {
    const handleClick = vi.fn();
    renderWithProviders(<TaskForm onClick={handleClick}></TaskForm>);
    fireEvent.click(screen.getByText("Add"));
    expect(handleClick).toHaveBeenCalledTimes(1);
  });
});
typescript unit-testing react-testing-library jsdom vitest
1个回答
0
投票

您的测试的问题是 TaskForm 不排除参数。所以你不能提供 onClick 函数来监视。 我用的是jest,所以实际的代码可能有点不同,但我相信原理是一样的。

您可以监视调度和/或检查 userInputVal 是否已设置 这就是我监视调度的方式:

const testStore = createStore();
const dispatchSpy = jest.spyOn(testStore, 'dispatch');
expect(dispatchSpy).toHaveBeenCalledWith('the task it is called with');

我在您的测试中没有看到任何类型的商店。也许这是 Vitest 的事情,但我认为你应该拥有它,特别是如果你想监视调度。

您已经在其他测试中检查了输入中的值,因此您可以对这个测试执行类似的操作。

© www.soinside.com 2019 - 2024. All rights reserved.