chore: make jest a peer dependency with v29/v30 support

Move jest from dependencies to peer dependencies, allowing users to
choose between Jest 29 and Jest 30.

The CLI now detects the Jest version at runtime and uses the
appropriate environment:
- Jest 29: Uses standard jest-environment-jsdom
- Jest 30: Uses a custom environment based on @jest/environment-jsdom-abstract
  with fixes for Web API globals (fetch, streams, Error, etc.)

The cross-fetch polyfill is only injected for Jest 29, as with Jest 30+
our patched Jest environment is used. The network request blocker is made
MSW-compatible by checking if fetch was wrapped before blocking.

Jest 30 (with jsdom v27) fixes `Could not parse CSS stylesheet`
warnings/errors when testing components from @backstage/ui or other
packages using CSS `@layer` declarations.

New peer dependencies (install based on your Jest version):
- jest (required, ^29 or ^30)
- Jest 29 requires: jest-environment-jsdom
- Jest 30 requires: @jest/environment-jsdom-abstract, jsdom

Production code changes for jsdom 27 testability:
- AppIdentityProxy: extract navigateToUrl method for spying
- LiveReloadAddon: export utils.reloadPage for spying
- collect.ts: export internal.resolvePackagePath for mocking

MockFetchApi: evaluate global.fetch at call time instead of construction
time, allowing MSW to patch fetch after MockFetchApi is constructed.

Test adaptations for jsdom 27:
- Use RGB values instead of named colors in CSS assertions
- Update error format expectations (hyphenated type names, SyntaxError
  instead of FetchError for JSON parse errors)
- Simplify URL error assertions for cross-version compatibility
- Fix accessible name whitespace handling for external links
- Use history.replaceState for location mocking (non-configurable)
- Use fireEvent.blur for contentEditable elements
- Move async assertions inside waitFor for race conditions
- Remove Blob.prototype.text polyfill (now native)
- Remove test case using credentials in plugin:// URLs

Test adaptations for Jest 30:
- Replace `expect.objectContaining([...])` with direct array equality
- Replace `expect.objectContaining({ length: N })` with
  `expect.any(Array)` + separate `toHaveLength()` assertions
- Use child process for native Node.js module resolution in
  collect.test.ts to work around Jest 30's resolver behavior
- Update snapshot headers for new Jest format

Also removes the jest-haste-map patch which is no longer needed.

Signed-off-by: Johan Persson <johanopersson@gmail.com>
This commit is contained in:
Johan Persson
2025-12-01 09:33:31 +01:00
parent 6dd4fdfae0
commit cd0b8a11a3
47 changed files with 1764 additions and 1227 deletions
@@ -15,14 +15,9 @@
*/
import { createMockDirectory } from '@backstage/backend-test-utils';
import { collectConfigSchemas } from './collect';
import { collectConfigSchemas, internal } from './collect';
import path from 'path';
// cwd must be restored
const origDir = process.cwd();
afterAll(() => {
process.chdir(origDir);
});
import { execSync } from 'child_process';
const mockSchema = {
type: 'object',
@@ -37,6 +32,36 @@ const mockSchema = {
describe('collectConfigSchemas', () => {
const mockDir = createMockDirectory();
// Jest 30's module resolver doesn't find nested node_modules in mock directories.
// Use a child process for native Node.js resolution instead.
const originalResolvePackagePath = internal.resolvePackagePath;
beforeAll(() => {
internal.resolvePackagePath = (name, options) => {
const basePath = (options && options.paths?.[0]) ?? process.cwd();
const baseDir = basePath.endsWith('.json')
? path.dirname(basePath)
: basePath;
try {
return execSync('node', {
input: `console.log(require.resolve(${JSON.stringify(
name,
)}, { paths: [${JSON.stringify(baseDir)}] }))`,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe'],
}).trim();
} catch {
const error = new Error(`Cannot find module '${name}'`);
(error as NodeJS.ErrnoException).code = 'MODULE_NOT_FOUND';
throw error;
}
};
});
afterAll(() => {
internal.resolvePackagePath = originalResolvePackagePath;
});
afterEach(() => {
mockDir.clear();
});
+13 -4
View File
@@ -37,6 +37,17 @@ const req =
? require
: __non_webpack_require__;
/**
* Exported for test mocking. Jest 30's module resolver has issues with
* nested node_modules, requiring tests to use an alternative resolution strategy.
* @internal
*/
export const internal = {
resolvePackagePath(name: string, options?: { paths: string[] }): string {
return req.resolve(name, options);
},
};
/**
* This collects all known config schemas across all dependencies of the app.
*/
@@ -62,11 +73,9 @@ export async function collectConfigSchemas(
const { name, parentPath } = item;
try {
pkgPath = req.resolve(
pkgPath = internal.resolvePackagePath(
`${name}/package.json`,
parentPath && {
paths: [parentPath],
},
parentPath ? { paths: [parentPath] } : undefined,
);
} catch {
// We can somewhat safely ignore packages that don't export package.json,