警告:测试中对 Formik 的更新未包含在 act(...)

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

当我 运行 我的测试时,即使测试有效,它也会向我发送警告。通过一些研究,我似乎必须将它放在 act 中,但它是同一回事

console.error
    Warning: An update to Formik 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 */
    
    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
       )

      at printWarning (node_modules/react-dom/cjs/react-dom.development.js:67:30)
      at error (node_modules/react-dom/cjs/react-dom.development.js:43:5)
      at warnIfNotCurrentlyActingUpdatesInDEV (node_modules/react-dom/cjs/react-dom.development.js:24064:9)
      at dispatch (node_modules/react-dom/cjs/react-dom.development.js:16135:9)
      at node_modules/formik/src/Formik.tsx:327:11

  console.error
    Warning: An update to Formik 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 */
    
    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
<div className={classes.root}>
            <Grid container alignItems="center" className={classes.h__full}>
                <Grid item sm={12} md={12} className={classes.w__full}>
                    <Alert
                        severity={message.status}
                        className={classes.alert}
                        style={{ visibility: message.message ? "visible" : "hidden" }}
                    >
                        {message.message}
                    </Alert>
                    <CreateSecretForm
                        onSubmit={handleSubmit}
                        initialValues={initialValues}
                        validationSchema={CreateSecretSchema}
                    />
                </Grid>
            </Grid>
        </div>

test code snippet

为什么会这样?

https://github.com/formium/formik/issues/1543

Formik 错误。就我而言,这发生在 运行 一个笑话测试时,它与 Formik 中的 validateOnMount 属性 有关。 我通过在我的断言中加入 waitFor 来解决这个问题:

    await waitFor(() =>
      expect(getByText('Component header')).toBeInTheDocument()
    )

请注意,在 act 中包装 jest 渲染不起作用,因为这是重新渲染