You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
The current testing environment is not configured to support act(...) with vitest and React 18 #1061
"@testing-library/jest-dom": "5.16.4",
"@testing-library/react": "13.1.1",
DOM Environment: jsdom or happy-dom (happens with both)
Problem description:
After upgrading to @testing-library/react@13.x and react@18.x with vitest. A lot of react tests throw the following warning:
Warning: The current testing environment is not configured to support act(...)
I noticed this after switching from jest to vitest, and not changing anything else. (The tests do not show this warning when using jest, but they they show it when using vitest in the same project).
I previously had an unrelated issue causing the same warning with Jest: #1057
I resolved that, by removing a bad implementation of act(). However this time the tests are identical, and works with 1 test-runner and not with another.
@stuarthallows and @dar5hak also both seem to be having the same problem as me (see my other issue here: #1057 for more details).
Additional information.
In my case, this is breaking unit tests completely because it logs thousands of these warnings and it just stops after around 10 tests are completed.
For me a lot of the errors start with rc-motion
Warning: The current testing environment is not configured to support act(...)
at Align (/Users/marklyck/colony/colony-frontend/node_modules/.pnpm/rc-align@4.0.12_ef5jwxihqo6n7gxfmzogljlgcm/node_modules/rc-align/lib/Align.js:45:23)
at DomWrapper (/Users/marklyck/colony/colony-frontend/node_modules/.pnpm/rc-motion@2.5.1_ef5jwxihqo6n7gxfmzogljlgcm/node_modules/rc-motion/lib/DomWrapper.js:28:34)
at /Users/marklyck/colony/colony-frontend/node_modules/.pnpm/rc-motion@2.5.1_ef5jwxihqo6n7gxfmzogljlgcm/node_modules/rc-motion/lib/CSSMotion.js:57:32
Which is probably running an animation with antd components. But I'm 99% sure that's a red-herring since the same tests and components work just fine with jest. (or testing-library/react@12 and react@17)
The workaround doesn't totally work for me. The initial error The current testing environment is not configured... to support act(...) goes away, but then I get act warnings I wouldn't have otherwise.
Worth noting that this also appears to be exclusive to React 18. If you downgrade everything to React 17 (including downgrading this library to v12), the act warnings go away and you also don't need to override the global anymore.
Reacted by Darshak Parikh, Richard Cooke, Mel, Carlos Núñez, Benja, Konstantin Tretiakov, Nathan Vasse, Vishnu Rana, Pavlin Angelov, we5a and 5 more
I raised a similar issue at vitest. But they think (and I kind of agree), that it has to be solved in testing-library.
tldr; of my vitest-issue:
when testing-library/react resolves IS_REACT_ACT_ENVIRONMENT it uses the first existing of self, window and global as global-object, which in may case is self
react access IS_REACT_ACT_ENVIRONMENT directly, which is probably globalThis or globallink.
in vitest / jsdom, globalThis and self are not the same object.
The fix
I think the fix is to add
if (typeof globalThis !== 'undefined') {
return globalThis
}
The workaround is define some kind of proxy-property on global this, that will make sure that self and globalThis have the same value of IS_REACT_ACT_ENVIRONMENT the code in setupFile.ts:
We're waiting on confirmation for vitest-dev/vitest#1146 (comment). We're matching the globalThis polyfill so it isn't obvious that we can or should change something.
shouldn't a polyfill only apply if the feature itself is not available? I would argue that if globalThis exists, you should use
it, and not the polyfill.
shouldn't a polyfill only apply if the feature itself is not available? I would argue that if globalThis exists, you should use it, and not the polyfill.
We can do that. The code shouldn't necessarily be considered a polyfill. It worked perfectly well when globalThis didn't exist. So there's definitely something wrong in vitest environments since they wouldn't support legacy code that works in any other environment.
We can still fix it by using globalThis if it exists. So feel free to send a PR. But older versions will continue to not work in vitest until they fix that issue on their side as well.
I've upgraded to the latest version of vitest (0.12.6 at the time of writing) and it still doesn't resolve the issue. Using the workaround @nknapphere does successfully get rid of the warnings
Thanks for creating that MR, @eps1lon. I think the issue I mentioned is indeed fixed with vitest@0.12.6
@stuarthallows I have just spent a couple of hours trying to find out why I also still get some act-warnings. Maybe you have a similar problem.
The following code is wrong, but the error is very hard to see
it("sends no access token after logout",async()=>{// ...awaitclickLogoutButton();awaitwaitForLogout();// ...})asyncfunctionclickLogoutButton(){awaitact(()=>{returnscreen.getByText("Logout").click();});}
There is an await act(), but the callback is a synchronous function. This leads to some bad "timing", so that the actual state-change is just after the act() call, but before the waitFor-call that is done inside waitForLogout()
The function clickLogoutButton should be either completely synchronous:
it("sends no access token after logout",async()=>{// ...clickLogoutButton();// <---- no "await"awaitwaitForLogout();// ...})functionclickLogoutButton(){// <--- no "async"act(()=>{// <--- no "await"screen.getByText("Logout").click();});}
or completely asynchronous
it("sends no access token after logout",async()=>{// ...awaitclickLogoutButton();awaitwaitForLogout();// ...})asyncfunctionclickLogoutButton(){awaitact(async()=>{// <--- added "async" to callbackscreen.getByText("Logout").click();});}
Reacted by Keerthivasan Sivasankar, tdiluzio, stepan-lylak, Cleumir Santos, Drew Hoover, Luka, AllanZhengYP, Hawkeye Parker, John D. Jameson, Olivier Tassinari and 4 more
Reacted by Luka, Hawkeye Parker, Peter Klingman and yourBadApple
There is an await act(), but the callback is a synchronous function. This leads to some bad "timing", so that the actual state-change is just after the act() call, but before the waitFor-call that is done inside waitForLogout()
This paragraph right here was a life-saver after two solid days of fighting through a react 18 upgrade.
Apparently, if you put find* calls inside an act, the timing somehow doesn't work out... it would be reasonable to think "more awaits better" in terms of timing, but for some reason, awaiting an act that awaits things doesn't work out well.
The results are extremely confusing and spooky - literally your test can pass and then error after they pass!
$ yarn test -- pages/Home
yarn run v1.22.19
warning From Yarn 1.0 onwards, scripts don't require "--" for options to be forwarded. In a future version, any explicit "--" will be forwarded as-is to the scripts.
$ jest pages/Home
PASS src/pages/Home/index.test.tsx
● Console
console.error
Warning: The current testing environment is not configured to support act(...)
This particular project is open source, and you can see the commit that fixed my failing tests here - it has several examples of "things that don't work if you wrap them in act":
Simply removing some of the act wrappers fixes the timing issues.
This should be covered by documentation maybe?
I know you're just pulling this functionality from react's own facilities, but their documentation doesn't cover this - and I suppose maybe their documentation can't be expected to cover the interplay with facilities provided by react-testing-library?
Not sure. This was extremely confusing and time consuming and seems like something almost everyone would run into at first.
Could it be detected and guarded against, with a better error message to guide people along maybe? 🤔
Reacted by Wesley, hekate, Antti Ahti, Dercilio Fontes, Sonja Musicki, Raphael Krut-Landau, stepan-lylak, Luka, bryansantamaria, Roman Bielte and 1 more
Worked just fine. I was proud of not using act even once in the entire project.
(btw, note my test is synchronous. async/await was only needed with more complex components)
I'm working on upgrade to React 18 + @TL/react 13 + @TL/user-event 14 👷
Following the recommendation in the docs I switched out of userEvent:
However, the more complex components would throw 'An update to Comp inside a test was not wrapped in act'.
Seems weird because I was under the impression the waitFor does that under the hood.
Swallowed my pride 😞 and fixed it by adding act:
awaitact(()=>waitFor(()=>user.click(screen.getByRole('button'))))// not as pretty as before, but works
Surprisingly in some cases I get 'The current testing environment is not configured to support act' (sadly I can't tell why it warns for certain components but not for others).
After hours of trying to fix it I found a solution completely by accident:
I hope this is helpful - either to the wonderful maintainers of TL or any user facing the same warning. 🙏
EDIT: I'm aware the callback in waitFor could be either callback: () => (void | Promise<void>). Still wrapping my head around all of this.
UPDATE: Some of my issues were because I useFakeTimers - this was solved by userEvent.setup({advanceTimers: jest.advanceTimersByTime}). I still faced many "testing environment is not configured to support act" warnings (mainly in components that use react-query 🤔) and ended up overriding console.error to ignore them.
FINAL(?) EDIT (2023-02-06): All of the above is one long workaround for an error caused by me not properly waiting for my components to load. Don't do it. Read my other comment.
Please don't do this! Read another comment I left below👇
Reacted by Rafał Stencel, Dercilio Fontes, Jan Mehlhorn, lemkaa, 배상우 / 코드싸이, Radosław Szalski and David Johnston
Reacted by binhphan009, Kapil Goyal and David Johnston
Tbh. I don't think it's good practice to put actions like 'click' into a 'waitfor'.
waitFor is for observation. It may end up in multiple clicks if you are not careful.
waitFor should also not be nested in 'act'.
Those may be pragmatic workarounds, but not proper solutions.
I am writing this for everybody who is new to testing-library, reading this thread and learning from it.
If these problems still occur, it's probably a bug, in testing-library or vitest.
Reacted by Ian da Conceição da Silva, Amnon Sadeh, Jaakko Juvonen, Lucas Rosa, 𝑵𝒂𝒎𝒏𝒊𝒌𝒂 𝑱𝒂𝒏𝒃𝒂𝒏𝒅𝒉𝒖, Björn Heiß, Alexander Kondratskiy, Jonas Holland, Radosław Szalski, David Roden and 1 more
I don't know if it helps, but I had the same error without using Vitest Warning: The current testing environment is not configured to support act(...)
And global.IS_REACT_ACT_ENVIRONMENT = true; didn't work for me
Reacted by yoleoagain, Krzywy14, Joshua Kleckner, Okada Genya, Dirk Roeleveld, Mehmet Yatkı, Serhii, Landon, 𝑵𝒂𝒎𝒏𝒊𝒌𝒂 𝑱𝒂𝒏𝒃𝒂𝒏𝒅𝒉𝒖, Hendrik Lammers and 2 more
@binhphan009 You're welcome, but in fact, a couple of months after I left that comment here, I re-visited my test suites and removed almost all of the act calls.
It turns out I wasn't properly waiting for my API-dependent components to load (I use react-query and I obviously mock the backend in these tests, but the wait still needed to be handled) so jest timed out because the UI wasn't ready.
Wrapping user.click in a waitFor and then again in an act is a bad workaround (as @nknapp rightfully points out).
btw, the curly braces are ANOTHER bad workaround: they just cause the callback provided to waitFor to NOT return the promise from user.click which slightly alters its behavior in our favor, but it's just an accident, not a proper solution.
I'm now back to using await user.click(screen.getByRole('button')) totally error-free.
Reacted by Ian da Conceição da Silva, Peter Mouland, Thiago Silva Ferreira, Etienne Maheu, mihajlo-grubjesic, Liran Elisha, Oleg Lysachok, kgsvg, Tonhao, Przemysław Batte and 5 more
Reacted by Rolv Apneseth, 𝑵𝒂𝒎𝒏𝒊𝒌𝒂 𝑱𝒂𝒏𝒃𝒂𝒏𝒅𝒉𝒖, Ivan Gonzalez and Fortunat Mutunda
Reacted by Dom Armstrong, SettingsStore, Rémi Birot-Delrue, Carlos Esteban Lopez Jaramillo, Marco polo, Steve Miller, Tom Fischer, Olivier Tassinari, David Roden and Oliver Bell
Hey guys! Idk if someone's still having problem with it, but await waitFor(async () => {}) resolved the warning to me.
Reacted by Charles Richardson, Ali Gradina, Mateus Andrade, gbonhoure, Anaïs Macé, Evan Lovely, Alexey Belozerov, Thibault Jan Beyer, Suryakumar Selvakumar, Blessan Mathew and 1 more
Also seeing this issue on jest. None of the workarounds have worked consistently
Reacted by wjureczkacribl, Caio Oliveira, Russell Osborne, Angus Ryer, David Cohen, Alex Stein, Francisco Teixeira, Layne, Silvia Marmol, Eric Jiang and 2 more
FYI for anyone using Jest with Ant Design (antd) or other rc-component libraries, I managed to get Copilot to eliminate these warnings. This was its analysis:
The issue is that rc-components schedules microtasks that fire state updates after the testing library's act() wrapper restores IS_REACT_ACT_ENVIRONMENT to its previous value. Simply setting globalThis.IS_REACT_ACT_ENVIRONMENT = true in setup files doesn't work because Jest runs modules in a sandboxed VM context where Node's globalThis isn't visible to react-dom.
The fix is to use Jest's sandboxInjectedGlobals config option:
You need both options. The globals option sets the value, and sandboxInjectedGlobals makes it visible to modules like react-dom running in Jest's sandbox.
Activity
MarkLyck commentedon May 4, 2022
I found a workaround that seems to work.
If you manually add
To the
setupFilethe warning will go away.This should of course be handled by
React testing libraryso it's not a proper fix. But it allows us to use vitest until this issue is resolved :)airjp73 commentedon May 5, 2022
The workaround doesn't totally work for me. The initial error
The current testing environment is not configured... to support act(...)goes away, but then I getactwarnings I wouldn't have otherwise.I've made a reproduction here: https://github.com/airjp73/vitest-act-reproduction
Worth noting that this also appears to be exclusive to React 18. If you downgrade everything to React 17 (including downgrading this library to v12), the act warnings go away and you also don't need to override the global anymore.
nknapp commentedon May 6, 2022
I raised a similar issue at vitest. But they think (and I kind of agree), that it has to be solved in testing-library.
tldr; of my vitest-issue:
testing-library/reactresolvesIS_REACT_ACT_ENVIRONMENTit uses the first existing ofself,windowandglobalas global-object, which in may case isselfreactaccessIS_REACT_ACT_ENVIRONMENTdirectly, which is probablyglobalThisorgloballink.vitest/jsdom,globalThisandselfare not the same object.The fix
I think the fix is to add
here:
react-testing-library/src/act-compat.js
Lines 5 to 28 in c8c93f8
The workaround
The workaround is define some kind of proxy-property on global this, that will make sure that
selfandglobalThishave the same value ofIS_REACT_ACT_ENVIRONMENTthe code insetupFile.ts:eps1lon commentedon May 7, 2022
We're waiting on confirmation for vitest-dev/vitest#1146 (comment). We're matching the
globalThispolyfill so it isn't obvious that we can or should change something.nknapp commentedon May 13, 2022
shouldn't a polyfill only apply if the feature itself is not available? I would argue that if
globalThisexists, you should useit, and not the polyfill.
eps1lon commentedon May 13, 2022
We can do that. The code shouldn't necessarily be considered a polyfill. It worked perfectly well when
globalThisdidn't exist. So there's definitely something wrong in vitest environments since they wouldn't support legacy code that works in any other environment.We can still fix it by using
globalThisif it exists. So feel free to send a PR. But older versions will continue to not work in vitest until they fix that issue on their side as well.airjp73 commentedon May 13, 2022
I haven't had a chance to test myself, but I believe this was fixed on vitest's end.
ulrichstark commentedon May 13, 2022
Yes can confirm that this issue is fixed for me with newest vitest version.
WonderPanda commentedon May 13, 2022
I've upgraded to the latest version of vitest (0.12.6 at the time of writing) and it still doesn't resolve the issue. Using the workaround @nknapp here does successfully get rid of the warnings
stuarthallows commentedon May 14, 2022
Also not fixed for me with vitest 0.12.6, Nor does the workaround prevent the warnings.
nknapp commentedon May 28, 2022
Thanks for creating that MR, @eps1lon. I think the issue I mentioned is indeed fixed with vitest@0.12.6
@stuarthallows I have just spent a couple of hours trying to find out why I also still get some
act-warnings. Maybe you have a similar problem.The following code is wrong, but the error is very hard to see
There is an
await act(), but the callback is a synchronous function. This leads to some bad "timing", so that the actual state-change is just after theact()call, but before thewaitFor-call that is done insidewaitForLogout()The function
clickLogoutButtonshould be either completely synchronous:or completely asynchronous
Update: There are some eslint-rules, for TypeScript, that can detect such errors. I added the rules require-await and @typescript-eslint/await-thenable to my project.
mindplay-dk commentedon Aug 10, 2022
This paragraph right here was a life-saver after two solid days of fighting through a react 18 upgrade.
Apparently, if you put
find*calls inside anact, the timing somehow doesn't work out... it would be reasonable to think "more awaits better" in terms of timing, but for some reason, awaiting anactthat awaits things doesn't work out well.The results are extremely confusing and spooky - literally your test can pass and then error after they pass!
This particular project is open source, and you can see the commit that fixed my failing tests here - it has several examples of "things that don't work if you wrap them in act":
abtion/muffi.net@b70302f
Simply removing some of the
actwrappers fixes the timing issues.This should be covered by documentation maybe?
I know you're just pulling this functionality from react's own facilities, but their documentation doesn't cover this - and I suppose maybe their documentation can't be expected to cover the interplay with facilities provided by react-testing-library?
Not sure. This was extremely confusing and time consuming and seems like something almost everyone would run into at first.
Could it be detected and guarded against, with a better error message to guide people along maybe? 🤔
targumon commentedon Sep 6, 2022
With React 17 + @TL/react 12 + @TL/user-event 13 I had tests such as this:
Worked just fine. I was proud of not using
acteven once in the entire project.(btw, note my test is synchronous. async/await was only needed with more complex components)
I'm working on upgrade to React 18 + @TL/react 13 + @TL/user-event 14 👷
Following the recommendation in the docs I switched out of
userEvent:For most (simple) tests, this was fixed by adding
waitFor:However, the more complex components would throw 'An update to Comp inside a test was not wrapped in act'.
Seems weird because I was under the impression the
waitFordoes that under the hood.Swallowed my pride 😞 and fixed it by adding
act:Surprisingly in some cases I get 'The current testing environment is not configured to support act' (sadly I can't tell why it warns for certain components but not for others).
After hours of trying to fix it I found a solution completely by accident:
I hope this is helpful - either to the wonderful maintainers of TL or any user facing the same warning. 🙏
EDIT: I'm aware the callback in
waitForcould be eithercallback: () => (void | Promise<void>). Still wrapping my head around all of this.UPDATE: Some of my issues were because I
useFakeTimers- this was solved byuserEvent.setup({advanceTimers: jest.advanceTimersByTime}). I still faced many "testing environment is not configured to support act" warnings (mainly in components that use react-query 🤔) and ended up overridingconsole.errorto ignore them.FINAL(?) EDIT (2023-02-06): All of the above is one long workaround for an error caused by me not properly waiting for my components to load. Don't do it. Read my other comment.
Please don't do this! Read another comment I left below👇
2 remaining items
nknapp commentedon Feb 3, 2023
Tbh. I don't think it's good practice to put actions like 'click' into a 'waitfor'.
waitForis for observation. It may end up in multiple clicks if you are not careful.waitForshould also not be nested in 'act'.Those may be pragmatic workarounds, but not proper solutions.
I am writing this for everybody who is new to testing-library, reading this thread and learning from it.
If these problems still occur, it's probably a bug, in testing-library or vitest.
IanTorquato commentedon Feb 3, 2023
I don't know if it helps, but I had the same error without using Vitest
Warning: The current testing environment is not configured to support act(...)And
global.IS_REACT_ACT_ENVIRONMENT = true;didn't work for metargumon commentedon Feb 6, 2023
@binhphan009 You're welcome, but in fact, a couple of months after I left that comment here, I re-visited my test suites and removed almost all of the
actcalls.It turns out I wasn't properly waiting for my API-dependent components to load (I use react-query and I obviously mock the backend in these tests, but the wait still needed to be handled) so jest timed out because the UI wasn't ready.
Wrapping
user.clickin awaitForand then again in anactis a bad workaround (as @nknapp rightfully points out).btw, the curly braces are ANOTHER bad workaround: they just cause the callback provided to
waitForto NOT return the promise fromuser.clickwhich slightly alters its behavior in our favor, but it's just an accident, not a proper solution.I'm now back to using
await user.click(screen.getByRole('button'))totally error-free.sag1v commentedon Jul 5, 2023
@targumon So what were your findings and how did you resolve it? 😄
nikolyachikm commentedon Sep 14, 2023
had this error which randomly failed tests. in my case I had code like this (select an option in dropdown):
solution:
KimSchneider commentedon Oct 5, 2023
@targumon you teased an answer but I am missing code! 😅
Rita0156 commentedon May 22, 2024
const originalError = console.error;
beforeAll(() => {
console.error = (...args) => {
if (
/Warning.*not wrapped in act/.test(args[0]) ||
/The current testing environment is not configured to support act/.test(args[0])
) {
return;
}
originalError.call(console, ...args);
};
});
afterAll(() => {
console.error = originalError;
});
Danielvandervelden commentedon Jun 13, 2024
For those of you wondering changing the following
To this:
Fixed my issue. A.K.A. remove the act entirely and just
awaittheuserEvent.clickinstead.MichalGorskiOnegini commentedon Jun 26, 2024
@Danielvandervelden works indeed, dear legend. Tho the reason why this happens is nicely explained here, for those who have enough time to read through it: https://stackoverflow.com/questions/75448819/async-thunks-cause-warnings-in-tests-wrapped-in-act e.g https://codilime.com/blog/why-should-you-be-grateful-for-act-warnings-in-react-tests/
Lux-Sales commentedon Sep 19, 2024
Hey guys! Idk if someone's still having problem with it, but
await waitFor(async () => {})resolved the warning to me.william-will-angi commentedon May 24, 2025
Also seeing this issue on jest. None of the workarounds have worked consistently
Fix intermittent React act() failures with proper setup file
jakeboone02 commentedon Feb 2, 2026
FYI for anyone using Jest with Ant Design (
antd) or otherrc-componentlibraries, I managed to get Copilot to eliminate these warnings. This was its analysis: