fireEvent.click() 后的开玩笑测试结果(不含酶)

jest test results after fireEvent.click() (without enzym)

我想不通为什么点击这个测试框架的按钮后渲染状态没有改变。它适用于应用程序,但不适用于测试用例。我已经尝试阅读多个文档并使用 async/await waitForElementmoch renders 和多个 getBy* 组合……似乎没有任何效果。

我在沙盒上复制了代码 -> https://codesandbox.io/s/40pz9nj469

这是我要开始工作的代码块(位于 ./src/controls/Controls.spec.js):

it("Testcase: button 'Close Gate' changes to 'Open Gate' upon event click", () => {
  const { getByTestId } = render(<Controls />);
  const button = getByTestId("closed");

  expect(button).toHaveTextContent(/Close Gate/i);
  fireEvent.click(button);
  expect(button).toHaveTextContent(/Open Gate/i); // <<<fails here>>>
});

失败消息...

我被告知我们不允许使用酶,所以 mount/shallow 不是一个选项...

任何人有任何想法使这项工作?

我认为你的测试从一开始就没有意义。

您正在测试单击后该值是否发生变化,但如果 closed 值未发生变化,该值如何变化。

在单元测试的上下文中,对于您的组件,我会将您的测试分为两部分:

  1. 测试 toggleClosed 函数是否在单击按钮时被调用。
  2. 根据closed值测试是否显示正确的文本

所以这会给你类似的东西

测试函数是否被点击调用

    it("Testcase: button 'Close Gate' calls the toggleClosed function upon event click", () => {
      const mockFn = jest.fn();
      const { getByTestId } = render(<Controls toggleClosed={mockFn} />);
      const button = getByTestId("closed");

      fireEvent.click(button);

      expect(mockFn).toHaveBeenCalled();
    });

为了测试文本值是否正确,进行以下 2 项测试:

it("Testcase: should display 'Open Gate' when closed is true", () => {
  const { getByTestId } = render(<Controls closed={true} />);
  const button = getByTestId("closed");

  expect(button).toHaveTextContent(/Open Gate/i);
});

it("Testcase: should display 'Close Gate' when closed is false", () => {
  const { getByTestId } = render(<Controls closed={false} />);
  const button = getByTestId("closed");

  expect(button).toHaveTextContent(/Close Gate/i);
});

那么在我看来,您组件中的第二个按钮已经过全面测试