addons/shared/testUtils.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import type {MeasureMemoryOptions} from 'node:vm';
b69ab319import type {Json} from './typeUtils';
b69ab3110
b69ab3111import {measureMemory} from 'node:vm';
b69ab3112import {Logger} from '../isl-server/src/logger';
b69ab3113
b69ab3114export class MockLogger extends Logger {
b69ab3115 write() {
b69ab3116 // noop
b69ab3117 }
b69ab3118}
b69ab3119export const mockLogger = new MockLogger();
b69ab3120
b69ab3121export function clone<T extends Json>(o: T): T {
b69ab3122 return JSON.parse(JSON.stringify(o));
b69ab3123}
b69ab3124
b69ab3125/**
b69ab3126 * Returns a Promise which resolves after the current async tick is finished.
b69ab3127 * Useful for testing code which `await`s.
b69ab3128 */
b69ab3129export function nextTick(): Promise<void> {
b69ab3130 return new Promise(res => setTimeout(res, 0));
b69ab3131}
b69ab3132
b69ab3133export async function gc() {
b69ab3134 // 'node --expose-gc' defines 'global.gc'.
b69ab3135 // To run with yarn: yarn node --expose-gc ./node_modules/.bin/jest ...
b69ab3136 const globalGc = global.gc;
b69ab3137 if (globalGc != null) {
b69ab3138 await new Promise<void>(r =>
b69ab3139 setTimeout(() => {
b69ab3140 globalGc();
b69ab3141 r();
b69ab3142 }, 0),
b69ab3143 );
b69ab3144 } else {
b69ab3145 // measureMemory with 'eager' has a side effect of running the GC.
b69ab3146 // This exists since node 14.
b69ab3147 // 'as' used since `MeasureMemoryOptions` is outdated (node 13?).
b69ab3148 await measureMemory({execution: 'eager'} as MeasureMemoryOptions);
b69ab3149 }
b69ab3150}