Jest 告诉我使用 act,但 IDE 表明它已被弃用。什么是最好的?

问题描述 投票:0回答:1

对于是否使用

act
或其他东西感到困惑?

Jest 告诉我换行

act
:

“console.error,警告:测试中对 ContactFormController 的更新未包装在 act(...) 中。测试时,导致 React 状态更新的代码应包装在 act(...) 中”

IDE 告诉我

act
已弃用:

“‘act’的签名‘(callback: () => void | Promise): Promise”已弃用。ts(6387) index.d.ts(393, 4):该声明在此处被标记为已弃用。"

ChatGPT 告诉我 React 批量调用,所以你不需要换行:

“在 React 17 及更高版本中,您通常不需要在测试中手动将更新包装在 act 调用中。相反,React 会在 Jest 等测试环境中自动批量更新。”

当我删除

act
时,测试失败。

我应该用什么来替代

act

这是我的测试:

import '@testing-library/jest-dom'
import { act, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'

import ContactFormController from '.'

describe('Contact Form Controller tests', () => {
  it('should render loader and disable submit button on form submit', async () => {
    const component = render(<ContactFormController />)

    const submitBtn = component.getByTestId('contact-submit-button')

    await act(async () => {
      userEvent.type(component.getByLabelText(/^First Name/i), 'Captain')
      userEvent.type(component.getByLabelText(/^Last Name/i), 'Bob')
      userEvent.type(component.getByLabelText(/^Email/i), '[email protected]')
      userEvent.type(component.getByPlaceholderText(/^Greetings/i), 'Captain Ahoy')
      userEvent.click(submitBtn)
    })

    expect(component.getByRole('alert')).toBeInTheDocument()
    expect(submitBtn).toBeDisabled()
  })
reactjs jestjs ts-jest
1个回答
0
投票

我猜你正在使用 React >= 18.3.0 和 @testing-library/react <= 15.0.5.

您可以尝试更新到

@testing-library/[email protected]
,其中 包含修复,以便从
act
react-dom/test-utils
使用
react

此外,您还可以升级到

[email protected]
,其中包括 act
导出并安装 RTL 的可选对等部门
@types/[email protected]

现在您应该能够在测试中使用

act
而不会出现弃用警告。

© www.soinside.com 2019 - 2024. All rights reserved.