首页 > 解决方案 > act(() => promise.resolve()) 在我的测试中到底做了什么

问题描述

我有一些具有同步代码的测试,因为它使用获取响应。当我没有这行“await act(() => Promise.resolve());”时,我会收到此错误。但是一旦我添加了这一行,这个错误就会消失,我的测试会按照它的假设运行。我知道这不是误报,因为我检查了它登录到我的终端的快照。但我对这一行感到困惑。它如何针对我的应用程序中的承诺,或者它只是另一种编写强制 settimeout 函数的方式。

错误

    console.error
      Warning: An update to authenticator 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 */
      });
      /* assert on the output */

测试

    test('when click with no inputs will display a error message in the DOM', async () => {
        const { getByText } = render(<CreateForm />, {wrapper: AuthProvider});

        await act(() => Promise.resolve());

        fireEvent.click(getByText('Create'));

        expect(getByText('Please fill in all fields')).toBeInTheDocument();
    });

标签: reactjsjestjsreact-testing-library

解决方案


推荐阅读