1+ // This file and the act() implementation is sourced from react-testing-library
2+ // https://github.com/testing-library/react-testing-library/blob/c80809a956b0b9f3289c4a6fa8b5e8cc72d6ef6d/src/act-compat.js
13import { act as reactTestRendererAct } from 'react-test-renderer' ;
2- import { checkReactVersionAtLeast } from './checkReactVersionAtLeast ' ;
4+ import { checkReactVersionAtLeast } from './react-versions ' ;
35
46const actMock = ( callback : ( ) => void ) => {
57 callback ( ) ;
68} ;
79
8- type GlobalWithReactActEnvironment = {
9- IS_REACT_ACT_ENVIRONMENT ?: boolean ;
10- } & typeof globalThis ;
11- function getGlobalThis ( ) : GlobalWithReactActEnvironment {
12- // eslint-disable-next-line no-restricted-globals
13- if ( typeof self !== 'undefined' ) {
14- // eslint-disable-next-line no-restricted-globals
15- return self as GlobalWithReactActEnvironment ;
16- }
17- if ( typeof window !== 'undefined' ) {
18- return window ;
19- }
20- if ( typeof global !== 'undefined' ) {
21- return global ;
22- }
23-
24- throw new Error ( 'unable to locate global object' ) ;
10+ // See https://github.com/reactwg/react-18/discussions/102 for more context on global.IS_REACT_ACT_ENVIRONMENT
11+ declare global {
12+ var IS_REACT_ACT_ENVIRONMENT : boolean | undefined ;
2513}
2614
2715function setIsReactActEnvironment ( isReactActEnvironment : boolean | undefined ) {
28- getGlobalThis ( ) . IS_REACT_ACT_ENVIRONMENT = isReactActEnvironment ;
16+ globalThis . IS_REACT_ACT_ENVIRONMENT = isReactActEnvironment ;
2917}
3018
3119function getIsReactActEnvironment ( ) {
32- return getGlobalThis ( ) . IS_REACT_ACT_ENVIRONMENT ;
20+ return globalThis . IS_REACT_ACT_ENVIRONMENT ;
3321}
3422
3523type Act = typeof reactTestRendererAct ;
24+
3625function withGlobalActEnvironment ( actImplementation : Act ) {
3726 return ( callback : Parameters < Act > [ 0 ] ) => {
3827 const previousActEnvironment = getIsReactActEnvironment ( ) ;
@@ -47,8 +36,9 @@ function withGlobalActEnvironment(actImplementation: Act) {
4736 if (
4837 result !== null &&
4938 typeof result === 'object' &&
39+ // @ts -expect-error this should be a promise or thenable
5040 // eslint-disable-next-line promise/prefer-await-to-then
51- typeof ( result as any ) . then === 'function'
41+ typeof result . then === 'function'
5242 ) {
5343 callbackNeedsToBeAwaited = true ;
5444 }
@@ -87,12 +77,16 @@ function withGlobalActEnvironment(actImplementation: Act) {
8777 }
8878 } ;
8979}
80+ const getAct = ( ) => {
81+ if ( ! reactTestRendererAct ) {
82+ return actMock ;
83+ }
9084
91- const act = reactTestRendererAct
92- ? checkReactVersionAtLeast ( 18 , 0 )
85+ return checkReactVersionAtLeast ( 18 , 0 )
9386 ? withGlobalActEnvironment ( reactTestRendererAct )
94- : reactTestRendererAct
95- : actMock ;
87+ : reactTestRendererAct ;
88+ } ;
89+ const act = getAct ( ) ;
9690
9791export default act ;
9892export {
0 commit comments