/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unnecessary-condition, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-argument */ /* This file is taken from @testing-library/react (https://github.com/testing-library/react-testing-library/blob/main/src/act-compat.js) react@16 doesn't have exported act, this file solves it, taking it from react when possible */ import React from 'react'; import DeprecatedReactTestUtils from 'react-dom/test-utils'; const reactAct = typeof React.act === 'function' ? React.act : DeprecatedReactTestUtils.act; function getGlobalThis(): any { if (typeof globalThis !== 'undefined') { return globalThis; } if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } // @ts-expect-error types issues if (typeof global !== 'undefined') { // @ts-expect-error types issues return global; } throw new Error('unable to locate global object'); } function setIsReactActEnvironment(isReactActEnvironment: boolean) { getGlobalThis().IS_REACT_ACT_ENVIRONMENT = isReactActEnvironment; } function getIsReactActEnvironment() { return getGlobalThis().IS_REACT_ACT_ENVIRONMENT; } function withGlobalActEnvironment(actImplementation: any): any { return ( callback: () => { then?: (resolve: (value: unknown) => undefined, reject: (value: unknown) => undefined) => void; }, ) => { const previousActEnvironment = getIsReactActEnvironment(); setIsReactActEnvironment(true); try { // The return value of `act` is always a thenable. let callbackNeedsToBeAwaited = false; const actResult = actImplementation(() => { const result = callback(); if (result !== null && typeof result === 'object' && typeof result.then === 'function') { callbackNeedsToBeAwaited = true; } return result; }); if (callbackNeedsToBeAwaited) { const thenable = actResult; return { then: (resolve: (value: unknown) => undefined, reject: (value: unknown) => undefined) => { thenable.then( (returnValue: unknown) => { setIsReactActEnvironment(previousActEnvironment); resolve(returnValue); }, (error: unknown) => { setIsReactActEnvironment(previousActEnvironment); reject(error); }, ); }, }; } else { setIsReactActEnvironment(previousActEnvironment); return actResult; } } catch (error) { // Can't be a `finally {}` block since we don't know if we have to immediately restore IS_REACT_ACT_ENVIRONMENT // or if we have to await the callback first. setIsReactActEnvironment(previousActEnvironment); throw error; } }; } const act: (callback: () => void) => Promise = withGlobalActEnvironment(reactAct); export {act};