我有下面这个组件的简单测试文件。我基于这个React文档https://reactjs.org/docs/test-utils.html#act进行测试。
import ReactDOM from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import App from './App'
import { screen } from '@testing-library/react'
let container: HTMLElement;
beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);
});
it('can render and update a counter', () => {
  act(() => {
    ReactDOM.createRoot(container).render(<App />);
  });
  const title = screen.getByText('My App');
  expect(title).toBeInTheDocument()
});测试确实通过了,但我总是收到一个恼人的错误:
  Warning: A suspended resource finished loading inside a test, but the event was not wrapped in act(...).
  
  When testing, code that resolves suspended data should be wrapped into act(...):
  
  act(() => {
    /* finish loading suspended data */
  });
  /* 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当我从使用Reactive惰性加载的组件中移除时,错误消息就会消失。,那么我如何在没有这种反应18问题的情况下测试反应延迟加载呢?
这是我的setupTest.ts
import '@testing-library/jest-dom';下面是我的package.json依赖项
"dependencies": {
    "@react-spring/web": "^9.4.5",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "styled-components": "^5.3.5"
 },
"devDependencies": {
    "@react-spring/types": "^9.4.5",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.1",
    "@types/react": "^18.0.9",
    "@types/react-dom": "^18.0.5",
    "@types/styled-components": "^5.1.25",
    "@typescript-eslint/eslint-plugin": "^5.36.1",
    "@typescript-eslint/parser": "^5.36.1",
    "eslint": "^8.23.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-import-resolver-typescript": "^3.5.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-prettier": "^4.2.1",
    "eslint-plugin-react": "^7.31.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "prettier": "^2.7.1",
    "react-scripts": "5.0.1",
    "typescript": "^4.6.4"
  }我已经尝试过几种解决方案,比如使用await waitFor(...)、findBy(...)、从测试文件中删除act方法,但尚未成功。
我用Node 16.16
发布于 2022-09-02 13:59:32
我只是通过在测试结束时插入以下行来解决这个问题:
await screen.findByText('some text');我理解,由于更改发生在初始呈现之后,我们需要“告诉”测试库它所做的事情,并等待它的到来。然后,它不需要act()包装呈现方法。
发布于 2022-09-02 04:38:54
你试过把你的
const title = screen.getByText('My App');在act(){.}内的代码行?
https://stackoverflow.com/questions/73577586
复制相似问题