From 9087c0c363713e4399cce6d55f449bb82336f4a0 Mon Sep 17 00:00:00 2001 From: overlookmotel Date: Sun, 3 Sep 2023 01:47:29 +0100 Subject: [PATCH] Tests: Avoid instrumenting modules used by testing infrastructure [fix] Fixes #474. --- jest.config.js | 2 ++ test/support/register.js | 25 +++++++++++++++++++++---- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/jest.config.js b/jest.config.js index c06593a1..fb0ecd13 100644 --- a/jest.config.js +++ b/jest.config.js @@ -26,6 +26,8 @@ module.exports = { '/test/support/register.js' ], testSequencer: '/test/support/sequencer.js', + // Disable babel-jest transformation + transform: {}, // Jest by default uses a number of workers equal to number of CPU cores minus 1. // Github Actions runners provide 2 cores and running with 2 workers is faster than 1. ...(process.env.CI && {maxWorkers: '100%'}) diff --git a/test/support/register.js b/test/support/register.js index a27c94ee..43443126 100644 --- a/test/support/register.js +++ b/test/support/register.js @@ -3,22 +3,39 @@ * Tests install require hook to intrument test files' code * ------------------*/ -/* eslint-disable import/order, import/newline-after-import */ +/* eslint-disable import/order, import/no-dynamic-require, global-require */ 'use strict'; +// Imports +const { + useInternalModuleCache, useGlobalModuleCache, usingInternalModuleCache, Module +} = require('../../lib/shared/moduleCache.js'); + // Patch filesystem for virtual fixtures files require('./fixturesFs.js'); +// Pre-load `fast-json-stable-stringify`. +// `jest-light-runner` imports `jest-snapshot` which requires `@jest/transform`. +// After `jest-light-runner`'s worker loads the test file, it runs a method on `jest-snapshot` +// which causes `@jest/transform` to lazily require `fast-json-stable-stringify`. +// Trigger this now, so `fast-json-stable-stringify` is not loaded later and unnecessarily instrumented. +// `createScriptTransformer()` when called with no arguments throws an error before it does anything. +const {createRequire} = Module, + jestLightRunnerPath = require.resolve('jest-light-runner'), + jestSnapshotPath = createRequire(jestLightRunnerPath).resolve('jest-snapshot'), + jestTransformPath = createRequire(jestSnapshotPath).resolve('@jest/transform'); +if (Module._cache[jestTransformPath]) { + const jestTransform = require(jestTransformPath); + jestTransform.createScriptTransformer().catch(() => {}); +} + // Install register require hook. // Disable instrumentation cache. Tests run in multiple threads, so it'd be read from and written to // concurrently unless disabled. require('../../register.js')({cache: false}); // Use internal module cache to avoid transpiling modules -const { - useInternalModuleCache, useGlobalModuleCache, usingInternalModuleCache -} = require('../../lib/shared/moduleCache.js'); useInternalModuleCache(); // Modules