1

我无法弄清楚为什么在单击此测试框架的按钮后渲染状态没有改变。它适用于应用程序,但不适用于测试用例。我尝试阅读多个文档并使用async/await waitForElement,moch 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>>>
});

失败消息...

在此处输入图像描述

有人告诉我我们不允许使用酶,所以这里不能选择安装/浅...

有人有任何想法来完成这项工作吗?

4

1 回答 1

1

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

您正在测试单击后该值是否已更改,但如果该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);
});

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

于 2019-01-31T05:47:48.997 回答