React Hooks 和 Enzyme:React 不断告诉我将状态更新包装在 act(...) 中,即使我认为是这样

Hir*_*oki 5 reactjs jestjs react-dom enzyme react-hooks

我一直在自学如何使用enzyme和测试 React 组件jest,但我对如何测试使用 React hooks 的已安装组件一无所知。

这是该组件的简化版本......

  const [records, setRecords] = useState([]);

  const onChange = async ({ value }) => {
    try {
      const request = await searchRecords();

      console.log("Before setRecords");

      setRecords(request.results);

      console.log("After setRecords");
    } catch (error) {  /* error handling */ }
  }

Run Code Online (Sandbox Code Playgroud)

测试代码看起来像...

let wrapped;

describe("Sample", () => {
  beforeEach(() => {
    jest.clearAllMocks();
    wrapped = mount(
      <Provider store={createStore(reducers, {})}>
        <Sample />
      </Provider>
    );
    api.mockImplementation(() => ({ results: searchResult }));
  });

  afterEach(() => {
    wrapped.unmount();
  });

  it("shows items in the search box", () => {
    wrapped.find("#searchField")
      .simulate("change", { target: { value: "blah blah" } });
    // This triggers "onChange" function

    wrapped.update();

    expect(wrapped.find("li").length).toEqual(10);  
    // If "setRecords()" hook works, there will be 10 "li" elements
  });
});

Run Code Online (Sandbox Code Playgroud)

测试本身通过了,但我在 CLI 中看到以下消息。

Warning: An update to SearchBox inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
Run Code Online (Sandbox Code Playgroud)

按照警告消息中提供的链接,我包围了更新状态的行。

IE

act(() => {
  wrapped.find("#searchField").simulate("change", { target: { value: "red" } });
});
Run Code Online (Sandbox Code Playgroud)

尽管如此,警告消息仍然存在。为了以防万一,我包围了该mount(...) 部分,但这并没有改变任何东西。

在React的文档测试示例中,enzyme没有使用,所以我觉得React Hooksenzyme.

我们如何在仍在使用的同时删除警告消息enzyme?或者说,enzyme真的不兼容吗?

任何建议将被认真考虑。