当前的测试环境未配置为支持ACT(...) - @testing -library/react

发布于 2025-01-23 21:43:56 字数 4408 浏览 3 评论 0 原文

我正在尝试将项目升级为React 18,一切都以DEV和生产模式在浏览器中起作用。但是,在升级到最新版本的@testing-library/react 我的某些单元测试失败,其中很多正在记录以下警告:

  console.error
    Warning: The current testing environment is not configured to support act(...)

      at printWarning (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:86:30)
      at error (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:60:7)
      at isConcurrentActEnvironment (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:25057:7)
      at warnIfUpdatesNotWrappedWithActDEV (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:27351:12)
      at scheduleUpdateOnFiber (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:25292:5)
      at setLoading (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:17342:16)
      at _callee2$ (node_modules/.pnpm/@[email protected][email protected]/node_modules/@cubejs-client/react/src/hooks/cube-query.js:56:7)

我做的第一件事是检查我的版本,已清除节点。模块和锁定文件以防万一:

  • react 18.0.0
  • react-dom 18.0.0
  • @testing-library/react 版本:“ 13.1。 1英寸,
  • 测试框架和版本:“ jest”:“ 27.5.1”,
  • dom环境:JSDOR 16.7.0,

但一切看起来都正确吗?

我检查了React 18的迁移文档: 这说明最新版本的@testing-library/react 不应需要 globalthis.is_react_act_environment = true 设置。

但是我尝试在测试进行之前手动设置该设置。但这也没有解决,(我尝试过几个版本)

// @ts-ignore
global.IS_REACT_ACT_ENVIRONMENT = true
// @ts-ignore
globalThis.IS_REACT_ACT_ENVIRONMENT = true
// @ts-ignore
self.IS_REACT_ACT_ENVIRONMENT = true
// @ts-ignore
window.IS_REACT_ACT_ENVIRONMENT = true
// @ts-ignore
this.IS_REACT_ACT_ENVIRONMENT = true

这些都没有修复警告或单元测试。

我正在使用Jestv。27.x和JSDOM,我认为这将是最常见的配置?因此,我很惊讶地遇到这个错误吗?

这是我的笑话

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
  moduleNameMapper: {
    '^src/(.*)$': '<rootDir>/src/$1',
    '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
  },
  transform: {
    '^.+\\.(t|j)sx?$': ['ts-jest'],
  },
  setupFilesAfterEnv: ['./src/setupTests.tsx'],
  modulePathIgnorePatterns: ['src/common/config.ts'],
  coverageReporters: ['text', 'json'],
}

I'm trying to upgrade my project to React 18, everything works in dev and production mode in the browser. But after upgrading to the latest version of @testing-library/react some of my unit tests are failing and a lot of them are logging the following warning:

  console.error
    Warning: The current testing environment is not configured to support act(...)

      at printWarning (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:86:30)
      at error (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:60:7)
      at isConcurrentActEnvironment (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:25057:7)
      at warnIfUpdatesNotWrappedWithActDEV (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:27351:12)
      at scheduleUpdateOnFiber (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:25292:5)
      at setLoading (node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom.development.js:17342:16)
      at _callee2$ (node_modules/.pnpm/@[email protected][email protected]/node_modules/@cubejs-client/react/src/hooks/cube-query.js:56:7)

First thing I did was check my versions, cleared node modules and lock file just in case:

  • react 18.0.0
  • react-dom 18.0.0
  • @testing-library/react version: "13.1.1",
  • Testing Framework and version: "jest": "27.5.1",
  • DOM Environment: jsdom 16.7.0

But everything looks right?

I checked the migration docs for React 18: https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html
Which says the latest version of @testing-library/react shouldn't require the globalThis.IS_REACT_ACT_ENVIRONMENT = true setting.

But I tried setting that manually anyway before my tests run. But that didn't fix it either, (I tried several versions)

// @ts-ignore
global.IS_REACT_ACT_ENVIRONMENT = true
// @ts-ignore
globalThis.IS_REACT_ACT_ENVIRONMENT = true
// @ts-ignore
self.IS_REACT_ACT_ENVIRONMENT = true
// @ts-ignore
window.IS_REACT_ACT_ENVIRONMENT = true
// @ts-ignore
this.IS_REACT_ACT_ENVIRONMENT = true

None of those fixes the Warning or the unit tests.

I'm using jest v. 27.x with jsdom which I imagine would be the most common configuration? So I'm quite surprised to be running into this error?

Here is my jest.config

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
  moduleNameMapper: {
    '^src/(.*)

Any ideas why a relatively simple setup like this, would be running into this warning with RTL v. 13.1.1?

: '<rootDir>/src/$1', '\\.(css|less|scss|sass)

Any ideas why a relatively simple setup like this, would be running into this warning with RTL v. 13.1.1?

: 'identity-obj-proxy', }, transform: { '^.+\\.(t|j)sx?

Any ideas why a relatively simple setup like this, would be running into this warning with RTL v. 13.1.1?

: ['ts-jest'], }, setupFilesAfterEnv: ['./src/setupTests.tsx'], modulePathIgnorePatterns: ['src/common/config.ts'], coverageReporters: ['text', 'json'], }

Any ideas why a relatively simple setup like this, would be running into this warning with RTL v. 13.1.1?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

不即不离 2025-01-30 21:43:56

在我的情况下,此警告出现了,因为我意外地导入了 ACT react-dom/test-utils 而不是@testing-library/react 。修复进口使警告消失了。

In my case this warning was appearing because I had accidentally imported act from react-dom/test-utils instead of @testing-library/react. Fixing the import made the warning disappear.

鲸落 2025-01-30 21:43:56

就我而言,发生这种情况是因为我在V12中实施了无用的行为。

await act(async () => {
      const hours = await screen.findByText('-6h')
      expect(hours).toBeInTheDocument()
    })

在此测试中,我删除了围绕我的主张的无用行为,并解决了有关“未配置为支持法案的环境”的警告。

就我而言,此特定的测试升级到V13后失败了,这就是我试图清理它的方式。

警告信息基本上无助于调试此消息。

In my case this happened because I had a useless act that I implemented as a workaround in v12.

await act(async () => {
      const hours = await screen.findByText('-6h')
      expect(hours).toBeInTheDocument()
    })

I removed the useless act around my assertion in this test, and the warning about the "environment not configured to support act" was resolved.

In my case, this particular test was failing after upgrading to v13, which is how I ended up trying to clean it up.

The warning message was essentially not helpful in debugging this.

初心 2025-01-30 21:43:56

相关 gh问题

从某种意义上说,警告与测试环境无关,而是由有问题的测试引起的。

除了在我的情况下,除了在前两个答案中已经建议的修复程序外,问题还包括等待 waitfor 调用,这导致所有后续的测试用例都产生警告。

waitFor(...) // ❌ Causes warning.
await waitFor(...) // ✅ Works.

Relevant GH issue.

The warning is misleading in a sense that it has nothing to do with the testing environment but is rather caused by a problematic test.

In addition to the fixes already suggested in the top 2 answers, in my case, the problem was in a forgotten await for waitFor call which caused all the subsequent test cases to produce the warning.

waitFor(...) // ❌ Causes warning.
await waitFor(...) // ✅ Works.
空气里的味道 2025-01-30 21:43:56

如果测试的代码在测试完成后执行回调,也可能会发生这种情况。例如用户输入上的油门。

可以通过使用完成回调提供的回调通过jest提供或使计时器完成,可以避免使用它。立即使用计时器模拟

It can also happen if the tested code has a timeout that executes a callback after the test has finished. For instance with a throttle on a user input.

It can be avoided either by using the done callback provided by jest or by making the timers to finish instantly with the timer mocks.

荒岛晴空 2025-01-30 21:43:56

就我而言,问题是ACT()函数嵌套在ACT()中:

await act(async () => {
  await someFunction(); // This function also calls act() inside which causes error that OP mentions
  jest.advanceTimersByTime(500);
});

In my case the problem was act() function nested in act():

await act(async () => {
  await someFunction(); // This function also calls act() inside which causes error that OP mentions
  jest.advanceTimersByTime(500);
});
最佳男配角 2025-01-30 21:43:56

我没有发现全局标志不适合我的原因,所以以下猴子补丁为我解决了日志线

const originalConsoleError = console.error;
console.error = (...args) => {
  const firstArg = args[0];
  if (
    typeof args[0] === 'string' &&
    (args[0].startsWith(
      "Warning: It looks like you're using the wrong act()"
    ) ||
      firstArg.startsWith(
        'Warning: The current testing environment is not configured to support act'
      ) ||
      firstArg.startsWith('Warning: You seem to have overlapping act() calls'))
  ) {
    return;
  }
  originalConsoleError.apply(console, args);
};

,这是超级丑陋的,可能不是解决问题的最佳解决方案,但是又是

I didn't find the reason why the global flag was not working for me, so the following monkey patch resolved the log lines for me

const originalConsoleError = console.error;
console.error = (...args) => {
  const firstArg = args[0];
  if (
    typeof args[0] === 'string' &&
    (args[0].startsWith(
      "Warning: It looks like you're using the wrong act()"
    ) ||
      firstArg.startsWith(
        'Warning: The current testing environment is not configured to support act'
      ) ||
      firstArg.startsWith('Warning: You seem to have overlapping act() calls'))
  ) {
    return;
  }
  originalConsoleError.apply(console, args);
};

Yes, it's super ugly and likely not the best solution to the problem, but then again React does something pretty similar in their codebase.

┈┾☆殇 2025-01-30 21:43:56

package.json 中,添加以下内容:

  "jest": {

    "testEnvironment": "jsdom",

    "globals": {

      "IS_REACT_ACT_ENVIRONMENT": true

    }

  }

in package.json, add this:

  "jest": {

    "testEnvironment": "jsdom",

    "globals": {

      "IS_REACT_ACT_ENVIRONMENT": true

    }

  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文