mirror of
https://github.com/facebook/react-native.git
synced 2025-11-01 09:14:26 +00:00
a218b63969
Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/51696 Changelog: [internal] I realized that the Fantom module was being initialized before the execution of the test module itself (as part of the code generated by the runner), which could have problems if the test sets up the global environment that Fantom consumes. For example, if Fantom needs to use the `EventTarget` type from the global scope, it needs to wait until the initialization of the runtime so it can use it safely. This refactors all the code calling into Fantom as part of our infra to always initialize it lazily, so the first thing that runs as part of the test execution is the test itself (apart from our test setup, which is supposed to be side-effect free). Reviewed By: sammy-SC Differential Revision: D75681181 fbshipit-source-id: 91e4b903a49fcee59c5875e73db314cde0adea03
59 lines
1.7 KiB
JavaScript
59 lines
1.7 KiB
JavaScript
/**
|
|
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
*
|
|
* This source code is licensed under the MIT license found in the
|
|
* LICENSE file in the root directory of this source tree.
|
|
*
|
|
* @flow strict-local
|
|
* @format
|
|
*/
|
|
|
|
let initialized = false;
|
|
|
|
/**
|
|
* This method modifies the built-in `WeakRef.prototype.deref` method to make
|
|
* sure it is always called within the Event Loop in Fantom tests.
|
|
*
|
|
* Calling it outside the Event Loop can lead to inconsistent and confusing
|
|
* behavior as WeakRefs semantics are tied to the task + microtasks lifecycle.
|
|
*/
|
|
export default function patchWeakRef(): void {
|
|
if (initialized) {
|
|
return;
|
|
}
|
|
|
|
initialized = true;
|
|
|
|
// $FlowExpectedError[method-unbinding]
|
|
const originalDeref = WeakRef.prototype.deref;
|
|
|
|
// $FlowExpectedError[cannot-write]
|
|
WeakRef.prototype.deref = function patchedDeref<T>(this: WeakRef<T>): T {
|
|
// Lazily require the module to avoid loading it before the test logic.
|
|
const Fantom = require('@react-native/fantom');
|
|
|
|
if (!Fantom.isInWorkLoop()) {
|
|
throw new Error(
|
|
'Unexpected call to `WeakRef.deref()` outside of the Event Loop. Please use this method within `Fantom.runTask()`.',
|
|
);
|
|
}
|
|
|
|
return originalDeref.call(this);
|
|
};
|
|
|
|
const OriginalWeakRef = WeakRef;
|
|
|
|
global.WeakRef = function WeakRef(...args) {
|
|
// Lazily require the module to avoid loading it before the test logic.
|
|
const Fantom = require('@react-native/fantom');
|
|
|
|
if (!Fantom.isInWorkLoop()) {
|
|
throw new Error(
|
|
'Unexpected instantiation of `WeakRef` outside of the Event Loop. Please create the instance within `Fantom.runTask()`.',
|
|
);
|
|
}
|
|
|
|
return new OriginalWeakRef(...args);
|
|
};
|
|
}
|