mirror of
https://github.com/react/react-native.git
synced 2026-09-28 13:23:09 +08:00
Summary: Pull Request resolved: https://github.com/react/react-native/pull/58293 Changelog: [Internal] Reviewed By: vzaidman Differential Revision: D118513884 fbshipit-source-id: a33a81eab930ac29663410cf04163aebb87062ad
61 lines
1.8 KiB
JavaScript
61 lines
1.8 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()`.',
|
|
);
|
|
}
|
|
|
|
/* $FlowFixMe[invalid-this-arg] Error exposed after fixing this typing
|
|
* unsoundness in flow */
|
|
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);
|
|
};
|
|
}
|