首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >反应测试库-延迟加载-错误行为()

反应测试库-延迟加载-错误行为()
EN

Stack Overflow用户
提问于 2022-09-02 03:47:41
回答 2查看 95关注 0票数 0

我有下面这个组件的简单测试文件。我基于这个React文档https://reactjs.org/docs/test-utils.html#act进行测试。

代码语言:javascript
运行
复制
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()
});

测试确实通过了,但我总是收到一个恼人的错误:

代码语言:javascript
运行
复制
  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

代码语言:javascript
运行
复制
import '@testing-library/jest-dom';

下面是我的package.json依赖项

代码语言:javascript
运行
复制
"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

EN

回答 2

Stack Overflow用户

发布于 2022-09-02 13:59:32

我只是通过在测试结束时插入以下行来解决这个问题:

代码语言:javascript
运行
复制
await screen.findByText('some text');

我理解,由于更改发生在初始呈现之后,我们需要“告诉”测试库它所做的事情,并等待它的到来。然后,它不需要act()包装呈现方法。

票数 1
EN

Stack Overflow用户

发布于 2022-09-02 04:38:54

你试过把你的

代码语言:javascript
运行
复制
const title = screen.getByText('My App');

在act(){.}内的代码行?

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73577586

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档