fireEvent.click()(无enzym)后开玩笑的测试结果

时间:2019-01-31 05:18:51

标签: reactjs react-testing-library

我不知道为什么在此测试框架中单击按钮后渲染状态不会改变。它适用于应用程序,但不适用于测试用例。我尝试阅读多个文档并使用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>>>
});

失败消息...

enter image description here

有人告诉我我们不允许使用酶,因此这里不能选择mount / shallow ...

有人有什么想法可以使这项工作成功吗?

1 个答案:

答案 0 :(得分: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);
});

然后我认为您组件中的第二个按钮已经过全面测试

相关问题