Skip to content

Latest commit

 

History

History
445 lines (327 loc) · 53.6 KB

TESTING_DOCS.md

File metadata and controls

445 lines (327 loc) · 53.6 KB

Webpack Test Suite Structure

This document explains the structure of the test/ directory in the Webpack project using Jest. The directory is organized into multiple folders and files, each serving a specific purpose in testing various aspects of Webpack’s functionality.

Folder and File Breakdown

Directories come first, in alphabetical order, then the individual files worth their own note. Add a new entry where the alphabet puts it — the sections are deliberately unnumbered, so nothing has to be renumbered around it.

__snapshots__/

  • Purpose: Stores Jest snapshot files for comparing output consistency over time.
  • Usage: Used for testing UI components, serialized data, or expected module outputs.

benchmarkCases/

  • Purpose: Contains test cases for benchmarking Webpack's performance.
  • Usage: Measures build times, memory usage, and optimization impact.
  • Kinds of case (picked from the directory name):
    • build (default, e.g. many-modules-esm/) — a webpack.config.mjs plus an entry; measures one build per scenario (mode-development, mode-development-rebuild, mode-production).
    • *-unit (e.g. js-parser-unit/) — an index.bench.mjs exporting default (bench) => {…}; measures a piece of lib/ directly, with no scenarios.
    • *-runtime (e.g. many-modules-interop-runtime/) — measures the emitted bundle, not the build. The case is compiled once per scenario outside any measured region; the exec task then instantiates the output (runtime bootstrap plus every module factory that runs at import time) and calls the entry's exported run on it. The rebuild scenario is skipped, since it emits the same output.
    • *-local (e.g. realistic-app-large-local/) — a build case CI never measures, because simulation mode would exceed the job timeout. Run it with FILTER. The realistic-app sizes are small (realistic-app/, 48 components), realistic-app-medium-local/ (1,000), realistic-app-large-local/ (5,000) and realistic-app-very-large-local/ (20,000).
  • Writing a *-runtime case: the entry must export run(seed), do its work with that opaque seed, and return the result — otherwise the compiler folds the workload away and the bench measures nothing (both are checked and fail the run). The harness forces target: "node" and a commonjs2 library so the output can be instantiated in-process; generate large fixtures from options.mjs (setup()), as the build cases do.

exec is reported per scenario, so a development/production pair shows what scope hoisting and minification are worth at runtime.

cases/

  • Purpose: General test cases covering core functionalities.
  • Usage: Includes unit and integration tests for various modules and features.

configCases/

  • Purpose: Tests related to Webpack configurations.
  • Usage: Ensures that Webpack’s configuration (e.g., loaders, plugins) functions correctly.
  • Merged cases: optimization/minify-javascript/, css/minify-css/ and html/minify-html/ each run every directory inside them as one case, through helpers/mergedConfigCases.js. A directory keeps its own webpack.config.js, test.config.js (afterExecute, findBundle and moduleScope only) and test.filter.js, and builds into an output directory of its own. Its it titles open with its name. A case needing another hook, errors.js, warnings.js or infrastructure-log.js stays on its own. Each directory's inputs are copied as syntax fixtures too (below).

external/

  • Purpose: Every git submodule webpack checks out for testing — today the four spec corpora below and terser's, swc's and oxc's own tests. Nothing here is webpack's to edit: each directory belongs to its upstream project, and this repository only pins a commit.

test262-cases/

  • Purpose: ECMAScript test262 conformance test cases.
  • Usage: Git submodule — initialize with git submodule update --init test/external/test262-cases. Test runners: test/specCases/test262.spectest.js, which builds and runs each test in development, in production unminified (a failure there is webpack's own, not a minimizer's), and in production minified with webpack's printer. The minified mode skips the fn-name cases a renamed binding changes, keeps function and class names, and turns pure_getters, pure_conversions and pure_heritage off, as test262 reads names and properties that throw and converts and extends values that run code or throw on purpose. What each minimizer still fails is listed by reason in its MINIFIED_FAILURES table, and a listed case that passes fails the suite until removed. And test/specCases/minify-corpora.spectest.js, which minifies each test with webpack's printer and with terser.

html5lib-tests/

  • Purpose: WHATWG html5lib-tests tokenizer conformance cases for lib/html/syntax.
  • Usage: Git submodule — initialize with git submodule update --init --depth 1 test/external/html5lib-tests test/external/wpt: the runner reads both corpora. Test runner: test/specCases/html5lib.spectest.js (yarn test:html5lib) compiles every input as a webpack HTML entry to confirm the full pipeline handles it without crashing.

wpt/

  • Purpose: web-platform-tests, read two ways. html/syntax/parsing/resources/*.dat is the HTML tree-construction conformance corpus for parseHtml (html5lib-tests dropped its copy in 224991e). The .html documents under html/, conformance-checkers/ and dom/nodes, plus the declarations the css/**/parsing/ tests state a verdict for, are the printers' corpus: minifying must not change the DOM webpack's parser builds, the DOM Chrome builds, or the style Chrome computes.
  • Usage: Git submodule — initialize with git submodule update --init --depth 1 test/external/wpt (the repository is ~161k files, so keep it shallow). Test runners: test/specCases/html5lib.spectest.js (yarn test:html5lib), which also reads test/external/html5lib-tests — initialize both to run the whole suite — and test/specCases/syntaxEquivalence.spectest.js (yarn test:syntax-equivalence), whose browser tiers need a Chrome (CHROME_EXECUTABLE_PATH picks a binary other than the pinned build). A document that is not UTF-8 is skipped: the encoding fixtures are UTF-16, which no string API can read as source.

css-parsing-tests/

  • Purpose: CSS Syntax Level 3 conformance corpus for lib/css/syntax.
  • Usage: Git submodule — initialize with git submodule update --init test/external/css-parsing-tests. Test runner: test/specCases/cssParsing-webpack.spectest.js (yarn test:css-parsing) compiles every input as a webpack CSS entry to confirm the full pipeline handles it without crashing.

xml-conformance-suite/

  • Purpose: the W3C XML Conformance Test Suite (lddubeau's packaging) for parseHtml(…, { xml: true }) and the XML printer.
  • Usage: Git submodule — initialize with git submodule update --init --depth 1 test/external/xml-conformance-suite. Test runner: test/specCases/xmlconf.spectest.js (yarn test:xmlconf) compares every document the suite gives an expected output for to James Clark's canonical form, and checks that every document, minified or beautified, reads back to the canonical form of its source. Documents needing an external entity or DTD, and XML 1.1 ones, are counted rather than run. Without the submodule the suite registers a no-op and passes, so a green run then says nothing.

swc/

  • Purpose: swc's repository, read only under crates/swc_ecma_minifier/tests: its fixtures with their configs, the tests exec.rs and mangle.rs write inline, and the libraries it measures itself on. Each is held to terser's bytes like the terser corpora; a test with an expected.stdout, and every exec.rs test, also has its outputs run, and webpack's output may be no bigger than each fixture's recorded output.js, nor than what swc's port of a terser case records when its passing.txt lists it, unless SWC_SMALLER lists why.
  • Usage: Git submodule — initialize with git submodule update --init --depth 1 test/external/swc. Test runner: test/specCases/minify-corpora.spectest.js (yarn test:minify-corpora).

oxc/

  • Purpose: oxc's repository, read only under crates/oxc_minifier/tests: the source each test…( helper call in its Rust tests passes first, but TypeScript. Each is held to terser's bytes like the other corpora, and under the default minimizer's options every source of every corpus but test262 is also minified by oxc-minify: webpack's output may be no bigger than oxc's unless OXC_SMALLER lists why, and an oxc output that misprints is no lead.
  • Usage: Git submodule — initialize with git submodule update --init --depth 1 test/external/oxc. Test runner: test/specCases/minify-corpora.spectest.js (yarn test:minify-corpora), which also fails when the pin and the installed oxc-minify disagree.

terser/

  • Purpose: terser's own repository. Its test/compress cases and test/input files are two of the seven corpora lib/javascript/syntax-printer.js is held to (test262, swc's fixtures, exec.rs and mangle.rs tests, and oxc's tests are the other five): each source is minified by terser as published and by webpack's printer under several option sets, and the outputs, or the errors, must be byte-for-byte the same, but for what webpack's correct phase fixes. A case stating its expect_stdout also has each output run in terser's sandbox, which must print it — or, for expect_stdout: true, do whatever its input does, a throw or silence included.
  • Usage: Git submodule — initialize with git submodule update --init --depth 1 test/external/terser. Test runner: test/specCases/minify-corpora.spectest.js (yarn test:minify-corpora), which also fails when the pin and the installed terser disagree, so bumping the dependency means moving the pin with it. A new corpus is one entry in its CORPORA list.

fixtures/

  • Purpose: Stores sample/mock data used in tests.
  • Usage: Helps in creating consistent test cases with predefined inputs.
  • Syntax fixtures: fixtures/<css|html|xml|javascript>/<name>/index.<ext> is one input to unitCases/<lang>/invariants.unittest.js, which snapshots its tokens, parse, errors and prints, and holds it to the relations in helpers/syntaxInvariants/: spans, slices and purity for the parser, each cut short inside a construct held to spans and slices as well (reported as cut spans and cut slices); idempotence (cuts included), respellings, notices and meaning for the printer; behavior for JavaScript, with a compressing preset's output held to a second pass (idempotence under mangling, and residue), as yarn test:invariants:js holds the corpus; and scaling for a fixture built at a size. notices asks that the comments a minifier must keep survive (CSS and JavaScript legal notices, HTML conditional comments, server-side includes and <?…?>); meaning that the output reparses to what its source says (HTML and XML under every preset, CSS under beautify, JavaScript under the presets printing alone). XML's notices are the comments its minifier keeps (conditional comments, server-side includes, <![ and legal notices: a comment opening with ! or annotated @license or @preserve), and a compressing JavaScript preset owes only the banner's. Each CSS fixture is also held to agreement with css-tree. Which relation holds where, and why: COMPARE_TOOLS.md. JavaScript's per-fixture tests live in helpers/javascriptInvariants.js and run split across unitCases/javascript/invariants-shard-<n>.unittest.js by fixture name, so Jest runs them on parallel workers; purity and scaling stay in invariants.unittest.js, as they read every fixture together. Beside it, read by helpers/fixture.js:
    • options.json — print option sets. In JavaScript, "behavior": true on a set also runs its print against the source, which must print and throw the same (every script is run that way already under the presets printing alone). In HTML it renders the print and the source in the pinned Chrome (helpers/syntaxInvariants/behavior.js), at each width of RENDER_WIDTHS, and every element's boxes, its style attribute and the text a reader sees must match. In CSS it builds the elements either sheet's selectors reach and holds each one's computed style alike at every breakpoint a query names (compareStyles, at the default media; the print emulation stays the syntax-equivalence suite's). In XML it draws an SVG document and its print as images onto one canvas and holds them alike pixel for pixel, a channel moving past SVG_CHANNEL_TOLERANCE counting; pixels rather than elements, as a print may merge, convert or drop elements and draw the same, and a document whose root is no <svg> answers nothing, so marking one fails. Each marks only a SourceProcessor set, and its expected.json entries answer for the marked sets alone. "renderEmbeddedSource": "<name>" (or { "name", "options"?, "async"? }, async answering through a Promise) picks a renderer from helpers/embeddedRenderers.js, and { "regexp": "<source>", "flags"?: "<flags>" } stands for a RegExp anywhere in a set. Three keys send a set through readPrint:
      • "print": "<name>" picks the printer: process (the default), processAsync or the language's minimizer (cssMinify, htmlMinify, xmlMinify, jsMinify).
      • "visit" takes a visit spec (below) and fires its visitors during a process or processAsync print.
      • "minimizer": { "extractComments"?, "sourceMap"?, "buffer"?, "asset"? } sets the minimizer's other arguments: its extractComments argument, an input source map read from a file in the fixture's directory, a Buffer asset, and the asset's name (index.<ext> by default).
      • The snapshot holds the code (or throws: …), then what the minimizer returned beside it: everything, as JSON, under minimizer, so an absent list differs from an empty one; otherwise only the non-empty warnings, errors and extracted comments. The visit log and a recording renderer's offers come last.
    • parse.json — extra calls, each { "entry"?, "options"?, "visit"?, "pos"?, "fields"? }. Each runner's ENTRIES lists the entry names; an unknown name or key, or a key the entry does not take, throws.
      • entry is the public entry point by name; the document parse where absent.
      • options are its JSON options. A CSS skip.types lists NodeType names, which buildSkipSet turns into the skip set.
      • pos is the offset to start reading at.
      • "visit": true logs the entry's callbacks as one more snapshot entry.
      • fields logs reads made through A on every node the entry returns, as one more entry.
      • On SourceProcessor, "visit" takes a visit spec instead: { "types"?, "fields"?, "exit"?, "at"? }. It names the NodeTypes to visit, the reads to log on each enter, and whether exits are logged. at lists actions, each { "type", "on"?, "name"?, "source"? (a prefix), "index"?, "do", "with"? }, where do is skipChildren, stop, remove or replace (with is the text).
      • A read is name, value, source, range, loc or childCount; on a path also index or parent; or flag:<Flag>, fieldCount:<Field>, or rangeOf, startOf, endOf, textOf or sourceOf followed by :<Part>.
    • expected.json — known differences the invariants may report, each { "relation", "contains", "presets"?, "why" }: a finding of that relation whose repro holds contains, under one of presets (every preset where absent). An entry no finding needs fails as stale. A known bug's why opens with known bug:. In JavaScript, a behavior entry without presets answers for the sets options.json marks; one naming format or beautify for the invariants' own run.
    • fixed.css — an equivalent CSS input whose minified output must match the fixture's, with empty rules retained.
    • fixture.js — what JSON cannot hold, as CommonJS in Node 10 syntax (example):
      • source() returns the input, for one generated in code or holding a character no file can (a lone surrogate); the fixture then has no index.<ext>, and having both throws. Each snapshot entry of such an input longer than 400 characters holds its length, a digest and its first and last 200 characters.
      • source(n), declaring the parameter without a default (source.length says the fixture scales), also builds the input at size n; source() passes undefined for the size the snapshots hold. One test per runner holds every such fixture to scaling: it minifies the input at 64 and 128 under the first preset and counts, with V8's precise block coverage, how often each block of lib/ is entered. A block entered at least 16 times per unit of the larger size and more than 3 times as often as at the smaller fails: one entered once per unit doubles, one in a loop over the input quadruples. Counts, unlike time, are the same on every machine; native work (a RegExp, indexOf) is not counted, function call counts are left out (a call V8 inlined is not counted), and a runtime whose inspector cannot count synchronously skips the test. Only code compiled after counting starts is counted, so the runner loads a copy of the syntax for it with jest.isolateModules. An expected.json entry with "relation": "scaling" excuses one; a quadratic printer before #23377 grew 3.9–12.6× there.
      • Any other export is what { "fixture": "<export>" } stands for anywhere in options.json or parse.json, exactly where the JSON value would go, e.g. "transforms": { "comments": { "fixture": "keepLicense" } } or "renderEmbeddedSource": { "fixture": "myRenderer" }; an unknown name throws.
      • "visit": { "fixture": "<export>" }, in a print set or on SourceProcessor, calls the export with the visit log and the parser's enums, and the visitor map it returns fires; what it writes to the log is snapshotted.
      • "check": { "fixture": "<export>" }, in a print set or a run, calls the export with the printer's result (or the run's values) and { source, spec }, and snapshots what it returns as JSON: in a print before the visit and renderer logs, in a run last. Return a summary rather than asserting, and keep engine-dependent values (error messages) out of it. State an export keeps, such as a renderer's call count, is read back and reset by a check.
    • Size budget: a source longer than INVARIANT_BUDGET (20,000 characters, in helpers/fixture.js) gets every snapshot, and is held to spans and to idempotence, with what the preset keeps, under the first preset; the runner's purity test still reads it among all the others. Cuts, slices, respellings and the other presets print or parse it again per site or per preset: over the 122 generated CSS fillers (mostly 100–650 KB) they took 218 s of the 494 s suite, while a fixture under 5 KB costs about 50 ms. The threshold is the JavaScript runner's cap on running a script (BEHAVIOR_MAX_LENGTH), and spares every file fixture but three 40 KB HTML pages.
    • Deeper than the stack: a stage that runs out of stack (a RangeError, or a parser's own Not enough stack space refusal or parse error) snapshots overflows the stack, never the offset or the engine's wording, and the source is held to no relation.
    • TypeScript fixtures: fixtures/typescript/<name>/index.ts is one input to unitCases/typescript/node-type-stripping.unittest.js, which snapshots the tree parseProgram reads with typescript: true and compares it with the tree of Node.js's module.stripTypeScriptTypes output read as JavaScript (where Node.js has that API); where Node.js refuses the source, the parse must refuse it too, with unsupported-typescript-syntax exactly where Node.js says the syntax is not supported. An expected.json entry { "relation": "node", "why" } excuses a fixture whose tree must differ, such as one where Node.js writes no valid JavaScript. On every Node.js version, each fixture blanked as lib/typescript/blankTypeScript.js blanks it must read as JavaScript into the same tree.
    • Inline inputs: every unit test reads each source a syntax entry point takes with fixture(); JSON sources sit under fixtures/json/<name>/index.json, which no invariants runner reads. yarn lint:syntax-test-inputs (part of yarn lint) fails on a string or template literal, or an expression building one, given as the source to an entry point (parseA*, parseProgram, process, a minimizer's assets, …) or to a local helper that hands it on to one. It follows a source through names, renamed imports, for…of rows (destructured too), Object.entries/values/keys tables and computed lookups. It has no escape hatch: what a test expects, the arguments of string helpers such as escapeText, a preparsed tree and what fs or path return are not sources; an input built at a size goes in a fixture.js source().
    • Fuzzing: unitCases/<lang>/fuzz.unittest.js joins random sequences of the language's pieces into sources with fast-check (helpers/syntaxFuzz.js) and holds each to the same relations, shrinking a failure to its shortest source. The unit suite replays one fixed seed, 1,000 sources per language; the Fuzz workflow searches a random seed nightly at 20,000, prints it, and on a failure opens an issue for that language (or comments on the open one). Replay one with FUZZ_SEED=<seed> FUZZ_RUNS=<runs> yarn test:base --testPathPatterns="unitCases/<lang>/fuzz" --testTimeout=3000000. A shrunk failure becomes a fixture here, failing until the fix; a finding that is no bug goes in the test's known list with its why.

harness/

  • Purpose: What runs the suites, as opposed to what they test. Jest's lifecycle (globalSetup.js, globalTeardown.js, setupTestFramework.js), the patch-node-env.js test environment, runtimeCrashReporter.js, the case runner/, the snapshot/ resolver and matchers, benchmark/, and runtimes/.
  • runtimes/: The preload and setup files that let jest run under a non-Node runtime — bun-preload.js and bun-sandbox-setup.js for yarn test:bun, deno-worker-setup.js and deno-import-map.json for yarn test:deno. Wired in through jest.config.js and the test:base:bun / test:base:deno scripts.
  • Not helpers: a reusable assertion or fixture belongs in helpers/; harness/ is only for machinery the test runner itself loads.

helpers/

  • Purpose: Utility functions and scripts to assist in testing.
  • Usage: Provides reusable functions for mock data generation, cleanup, and assertions.

hotCases/

  • Purpose: Focuses on Webpack’s Hot Module Replacement (HMR) functionality.
  • Usage: Ensures live reloading and hot updates work correctly.
  • Every HMR change is covered twice: a case for the default output (JSONP on web, require on node, importScripts on webworker) and a twin under hotCases/esm-output/ with output.module: true and chunkFormat: "module". The ES module hot update wraps runtime code in a function, so it breaks in ways the default output never shows. A Worker twin there needs publicPath: "auto": a Node ES module worker can't import the harness's https:// default.

devServerCases/

  • Purpose: Proves Hot Module Replacement (HMR) works where users meet it: each case builds an app, serves it with a real webpack-dev-server and opens it in Chrome. hotCases/ drive the HMR runtime directly in jsdom; these go through the dev server's own client.
  • Usage: WebpackDevServer.longtest.js runs every <group>/<case>/ holding a test.config.js, from Node.js 22.15 up. A case has a webpack.config.js (the runner sets context, output.path and the dev server plugin), its sources and a test.config.js with devServer options, a page served at / (left out, the runner's default page loads /main.js; page: undefined serves the build's own index.html), and steps. The first step loads the page; each later one writes its edit and waits until the page shows its expect checks (an element's text or a computed style) and the error overlay. update: "hot" or "reload" says how the page took the edit, read from a marker on window that survives an in-place update but not a reload. A timeout quotes what the page logged; devServer: { client: { logging: "verbose" } } makes that tell more.

hotPlayground/

  • Purpose: A hand-driven counterpart to hotCases/ — those assert what an update does, this one lets you watch it happen in a browser. One panel per module type and ECMAScript form: an html entry, CommonJS, CSS, CSS modules, JSON via an import attribute, all three asset types, async and source-phase WebAssembly, import defer and an async chunk, plus a panel driving the HMR API itself (data/dispose, addStatusHandler, check, invalidate). Nothing here runs in CI.
  • Usage: yarn playground serves it on http://localhost:8080 with hot reloading on; edit any file and watch the page. See test/hotPlayground/README.md for what each file demonstrates.

memoryLimitCases/

  • Purpose: Contains test cases related to memory limits.
  • Usage: Ensures Webpack doesn’t exceed memory constraints.

sizeCoreReports/

  • Purpose: Whole applications for yarn test:size (below), whose report gives each one's total download in a Sample apps table.
  • A case is a directory with a webpack.config.mjs (or .js; an array builds one compiler per entry, each reported on its own row) and, optionally, an options.mjs whose exported setup() runs first to generate or install its sources (into generated/, which git ignores). The harness sets only context, output.path, mode: "production" when unset and quiet logging; everything else is the application's own configuration.
  • Today, each target with script (or CommonJS) and ES module output (-esm):
    • web: react-100, react-1k, react-5k and react-1k-esm, React apps of that many components (lazy routes, CSS modules, JSON, SVG) from the realistic-app benchmark's generator (test/harness/benchmark/create-app.mjs).
    • node: node-ssr and node-ssr-esm, that app rendered on the server by an http server with react-dom/server (test/harness/size/create-server.mjs).
    • webworker: webworker and webworker-esm, a message loop lazily loading 40 data tasks built on lodash-es and date-fns (test/harness/size/create-worker.mjs).
    • library: one small library built once per output.library.type, the types read from the schema.

specCases/

  • Purpose: Holds the runners for specification-conformance suites.
  • Files:
    • test262.spectest.js — yarn test:test262 --parts=3: defined whole, its ~175k tests overflow Jest's stack, so it always runs in parts, as CI does
    • test262-parser.spectest.js — yarn test:test262-parser
    • html5lib.spectest.js — yarn test:html5lib
    • syntaxEquivalence.spectest.js — yarn test:syntax-equivalence
    • cssParsing-webpack.spectest.js — yarn test:css-parsing
    • xmlconf.spectest.js — yarn test:xmlconf
    • minify-corpora.spectest.js — yarn test:minify-corpora; CI runs it in three parts, each claiming the next 100 sources of a group no other part took, and the last part to finish checks no table entry went unmet
    • js-fuzz.spectest.js — yarn test:js-fuzz: programs from test/helpers/jsFuzzProgram.js, in the sloppy ES5 terser's ufuzz writes, in modern syntax, as modules importing a fixed dep and as webpack-shaped bundles, minified under ufuzz's option sets, webpack's and random ones; the parser is held to acorn's tree on each program and output, the printer to the tree it read and to its own output, each output to what its program prints and exports, the default set's source map to its output and source, and the output to what it prints minified again. Needs no submodule; JS_FUZZ_SEED=<n> replays one seed, JS_FUZZ_SEED=random runs a new one named in the test's title, JS_FUZZ_PROGRAMS sets the programs per seed, and JS_FUZZ_RANDOM_OPTION_SETS sets how many random minifier option sets each generated program runs under.
    • xml-fuzz.spectest.js — yarn test:xml-fuzz: XML documents from test/helpers/xmlFuzzDocument.js, with XML declarations, DOCTYPE declarations, namespaces, comments, processing instructions, CDATA, references and deeply nested elements. Each generated document is held to test/helpers/syntaxInvariants/xml.js, including idempotence by default; set XML_FUZZ_CHECK_IDEMPOTENCE=0 to disable idempotence checks. XML_FUZZ_SEED=<n> replays one seed, XML_FUZZ_SEED=random runs a new one named in the test's title, and XML_FUZZ_INPUTS sets the inputs per seed.
    • syntax-fuzz.spectest.js — yarn test:syntax-fuzz, which CI does not run: stylesheets from test/helpers/cssFuzzStylesheet.js, built from mdn-data's property, at-rule, descriptor and selector grammars, and documents from test/helpers/htmlFuzzDocument.js, built from webref's element lists and the attribute tables in lib/html/data.js, with those stylesheets in <style> and style="". Each input is held to the syntax invariants and, in the Chrome launchBrowser starts, the HTML parser's tree to the browser's, each print's DOM facets and computed styles to its source's under the equivalence suite's option sets, and a beautified stylesheet's CSSOM to its source's. A finding is cut down, its letters spelled a and digits 0 where it still breaks, and reported. Each open defect is a syntax-fuzz-* fixture whose expected.json files every relation its input breaks; the browser's (styles, facets, cssom, dom) are read only here, where each such fixture is replayed in Chrome, and a seed's finding is known while one of those fixtures files its relation under its preset. SYNTAX_FUZZ_WRITE=1 writes each new finding as one, to be renamed and explained. The last test counts, per function named by what holds it, the lines of the CSS and HTML syntax-tokenizer.js, syntax-parser.js and syntax-printer.js no generated input reached, and fails where a count moved from syntax-fuzz.unreached.json: up, extend a generator to reach the new code; down, re-record with SYNTAX_FUZZ_UPDATE=1. It counts only over a run whose seeds all finished and cut nothing down, since a shrink fills caches a later input would have filled. SYNTAX_FUZZ_SEED=<n> replays one seed, SYNTAX_FUZZ_SEED=random runs a new one named in the test's title, and SYNTAX_FUZZ_INPUTS sets the inputs per seed; any of them skips the coverage test.

statsCases/

  • Purpose: Tests focused on Webpack’s statistical outputs.
  • Usage: Verifies correct bundle sizes, dependencies, and optimizations.

templates/

  • Purpose: The suite drivers — TestCases.js, ConfigTestCases.js, HotTestCases.js, WatchTestCases.js — each exporting describeCases(config).
  • Usage: The *.test.js / *.basictest.js / *.longtest.js files at the top of test/ are thin shims that call describeCases with one suite's options, so one driver serves every variant (targets, devtools, cache modes). Jest parallelizes per file, which is why the variants stay separate files rather than being folded into one.
  • Variants: variants.js holds the option sets the TestCases* and HotTestCases* shims run under, re-exported from each driver as variants. Add a variant by adding an entry there and one shim naming it — the shims stay separate files because jest parallelizes per file.
  • Note: templates/ is a sibling of the case directories it runs (cases/, configCases/, hotCases/, watchCases/), so a driver resolves paths from the shared test/ root via testRootDirectory (path.join(__dirname, "..")), never against __dirname.

typesCases/

  • Purpose: Type-checking tests, likely for TypeScript integration.
  • Usage: Ensures proper type definitions and compliance.

unitCases/

  • Purpose: Contains *.unittest.js unit tests for various functionalities.
  • Usage: Ensures individual modules and functions work as expected.
  • Layout: the syntax tests sit in one folder per language — javascript/ (tokenizer, parser, scope, printer), css/ and html/ (tokenizer, parser, printer), xml/ (printer) and json/ (printer, web-manifest). A printer's file holds both of its modes and the language's minifier, which drives the printer in its minify mode. The tests of the tooling/ scripts sit in tooling/. The rest, webpack's own classes such as JavascriptParser, stay at the top level.

watchCases/

  • Purpose: Tests for Webpack’s watch mode functionality.
  • Usage: Ensures file changes trigger correct rebuild behavior.

CodeSizeTestCases.size.js

  • Purpose: Measures how large the code webpack generates is, so a change to lib/ that grows (or shrinks) every bundle is visible.
  • Usage: yarn test:size builds every configCases/ case, plus every application in sizeCoreReports/ (reported as apps/<case>) — one plain Node.js process, outside jest, no worker pool — and writes a JSON report of what each case emitted: the raw, gzip, brotli and zstd size of every asset, plus a per-runtime-module breakdown (total bytes over the suite, how many cases emit it, the biggest single instance) — which is what shows which runtime grew, which is no longer emitted at all, and which one is simply large. The CI job (.github/workflows/code-size.yml) compares the report against the one main last uploaded, posts it as a pull request comment (updated in place on every push) and repeats it in the job summary.
  • What the comparison shows: how many cases, runtime modules and assets are changed / new / deleted / unchanged, then one row per changed asset — raw before → after, and the percentage each of gzip, brotli and zstd moved. A suite-wide total is deliberately not reported: a single number over 1400 cases hides which file moved, which is the only actionable part. The applications are the exception: a Sample apps table gives each one's whole download (gzip and raw, summed over its assets), which per-asset rows hide once code moves between chunks; only new, changed and deleted apps are listed open, unchanged ones folded below. With no baseline to compare against, the same table ranks the biggest assets instead.
  • It never fails. There is nothing to assert here and no size budget to breach: a growing bundle is information, not a defect. Cases whose expected result is a build error emit nothing and are reported as such, with the reason, rather than counted as failures.
  • Options: --output <file> (report path), --baseline <file> (report to compare against), --summary <file> (append the markdown comparison, e.g. $GITHUB_STEP_SUMMARY), --filter / --negative-filter (regexps matched against <category>/<case>, also read from FILTER / NEGATIVE_FILTER).
  • Note: the cases are built with the defaults a user gets — minification on, no output.pathinfo — not with the ConfigTestCases ones. Needs Node.js >= 22.15 for zstd.

unitCases/BannerPlugin.unittest.js

  • Purpose: Tests Webpack’s BannerPlugin functionality.
  • Usage: Ensures that the plugin correctly adds banners to the bundled files.

Writing a test

Behavior across rebuilds is a watchCases/ case, never a unit test calling compiler.run in a loop — output.clean, HMR update files, caches, anything one build leaves for the next. Each numbered step directory is one rebuild; its tests read WATCH_STEP, STATS_JSON and COMPILER, and the config can read the step from test/helpers/currentWatchStep. What the output can't show (which files a plugin touched) is recorded by a plugin in the config, which pushes a compilation.errors entry when it differs (watchCases/clean/removed-assets). A step needing time to pass waits in its own it with a longer timeout (watchCases/clean/hot-update-slow-rebuild).

Watch tests compare assets and diagnostics with a fresh, uncached build, check graph invariants and verify that fresh dependencies remain watched. Cached builds may retain extra resolution probes, and a watched directory covers its contents. Set strictWatchDependencies: true to require identical dependency sets in a fixture whose dependencies do not depend on build history. Keep runtime assertions; any skipFreshAssetContent, skipFreshWarnings or skipFreshCompilation exception needs a reason in test.config.js. See the watch dependency fixture for examples.

Snapshot printed code; assert everything else. When the thing tested is generated output — bundles, minified CSS/HTML, serialized ASTs, stats text — use toMatchSnapshot(), not expect(...).toBe(...) on fragments (which pins one substring and ignores every other byte). For behavior, invariants, equivalences and error paths use explicit expects; a snapshot there only records what happened to be true. Never snapshot a value some machine can't produce (a snapshot skipped without an optional browser or native binary is reported obsolete and fails the run there), and keep control characters out of snapshots (one NUL makes git treat the file as binary and hide its diff).

Example Test Case Structure

Many Webpack tests simulate small projects that are compiled during the test run.

For example, a configuration test may look like:

test/configCases/entry/simple/ index.js webpack.config.js expected.txt

Explanation:

  • index.js – entry file for the test project
  • webpack.config.js – configuration used by webpack
  • expected.txt – expected output or snapshot comparison

During the test run, webpack compiles this project and compares the result with the expected output to ensure behavior remains consistent.

Testing Framework

  • Jest is used for running tests.
  • Snapshots help maintain consistency in output.
  • Unit tests verify individual module functionality.
  • Integration tests ensure multiple components work together.

Splitting one file across workers

Jest runs each file in one worker, so a long suite in one file leaves the runner's other cores idle. --parts=<n> (read by jest.config.js) runs every matched file in n workers at once, as n projects whose coverage merges as usual; global setup and teardown run once. A file splits its own work with test/helpers/testParts.js: isInPart(key) tells whether this part runs the work named key, by a hash of the name, so nothing to measure or store; claimInPart(key) gives the work to the first part that asks, so a part that ends early takes more and the parts end together even where costs vary; and currentPart() returns [part, parts], e.g. to run a check once in part 1. Without the flag a file is one part and runs everything; a file that doesn't use the helper runs whole in every part, so pass the flag only where it runs files using it — e.g. CI's yarn cover:spec --parts=auto --maxWorkers=100%, where auto takes one part per core, capped at one per 4.5 GiB of memory (PART_MEMORY in jest.config.js) so a runner with many cores and little memory doesn't swap, and 100% one Jest worker per core, as Jest's default leaves one core idle. CI's spec job also runs the CSS, HTML and XML suites, which take a minute together and so run whole in every part.

Suites that drive a real browser

unitCases/ProfilingPlugin.unittest.js, unitCases/{css,html,xml}/behavior.unittest.js, unitCases/{css,html,xml}/invariants.unittest.js (on a fixture marking "behavior": true), specCases/syntaxEquivalence.spectest.js and WebpackDevServer.longtest.js launch a browser through test/helpers/launchBrowser.js, which drives all three engines with playwright-core. A browser that will not launch fails the suite — it is never skipped, so no environment can report these checks as passing without having run them. The helper only launches the builds playwright-core pins (Chrome for Testing for Chrome), never the machine's own Chrome, which moves with the machine rather than the lockfile: run yarn setup:browsers chrome first, or set CHROME_EXECUTABLE_PATH to point at another binary.

syntaxEquivalence.spectest.js is the one that reads more than one engine: EQUIVALENCE_BROWSER takes chrome, firefox or webkit, or a list of them that gives each part of a --parts run its own engine: CI runs EQUIVALENCE_BROWSER=chrome,firefox,webkit with --parts=3, all three at once on one runner. Fetch the browser first — yarn setup:browsers (all three, or name one; --with-deps also installs the system libraries Firefox and WebKit need) — which installs into playwright's own cache (PLAYWRIGHT_BROWSERS_PATH, defaulting to ~/.cache/ms-playwright on Linux). Firefox and WebKit are playwright's own builds of those engines, patched for automation, so FIREFOX_EXECUTABLE_PATH and WEBKIT_EXECUTABLE_PATH must point at such a build, never a stock browser; Chrome is the stock Chrome for Testing, and CHROME_EXECUTABLE_PATH takes any Chrome. It compares effects, never CSSOM text: a stylesheet by the styles elements built from its selectors compute, and where each one's 1lh lands on the 1/64px layout grid (a computed line-height serializes at six digits, which hides a rounded one), at the widths its queries switch on; a page by its DOM and its render, with the dark color scheme read through each frame's own. Media is emulated on Chromium only, the engine the filed defects were measured on, so only there is a stylesheet naming print also read under it. A defect only one engine has is filed against it with a reason opening <engine> only: rather than tolerated in all three, and each list must match exactly, so a defect the engine fixes fails until its entry goes. A workaround in the suite's own code gets the same treatment through a probe in ENGINE_QUIRKS.

Every engine is the build the lockfile pins: the ones the installed playwright-core ships. Dependabot bumps it in a browsers group of its own, so a new engine arrives in one pull request, and a defect or quirk it fixes fails there rather than under unrelated changes.

test:bun and test:deno run the Chrome-driven unit suites and WebpackDevServer.longtest.js too, on the same pinned Chrome.

Generated code is held to output.environment

No old browser runs in CI, so test/helpers/ecmaConformance.js asks the two questions one would answer, over every configCases case in ConfigTestCases and ConfigCacheTestCases. See that file for how it reads an environment.

  • Will it parse? Always on: every runtime module a build renders is parsed against the environment it was rendered for.
  • Will it run? restrictEnvironment: true in test.config.js removes from the bundle's realm what the target lacks, so webpack's guards are taken rather than stepped over. Web targets only.

Two more test.config.js fields: ecmaConformance: true widens the parse check to every emitted asset, so the case's own sources are held to its output.environment too, and ecmaConformanceExpected declares findings deliberate as regexps, each with its reason — one that stops matching fails the case.

ESM output is held to what a foreign bundler reads

test/helpers/analyzableConformance.js walks every output.module case the way another tool would: it takes the specifiers a lexer reports plus the new URL(…, import.meta.url) names only an AST sees, follows the literal ones from each entry, and asks two questions of what it reaches.

  • Does every chunk have a name someone else can follow? A chunk only __webpack_require__.e reaches is a finding, unless the build recorded why it kept the runtime form — performance.analyzableBailouts reads the same reasons — or an eval devtool hid every specifier inside a string.
  • Does every name it writes exist? A specifier naming a place inside the output that neither the assets nor the directory holds is a finding.

analyzableConformanceExpected in test.config.js declares findings deliberate as regexps, each with its reason — one that stops matching fails the case.

Under ecmaVersion/, the es5-* cases cover one runtime-emitting feature each (jsonp, importScripts, require and read-file chunk loading, workers and asset urls, css, hot updates, wasm, the library wrappers, Module Federation, the neutral platform); es-versions sweeps every rung of the esX ladder; environment-flags turns each flag off on its own against an otherwise current target, which a version sweep cannot do; and esm-environment repeats both over ESM output.

External test corpora

Upstream test suites webpack runs against but doesn't maintain — upstream's to change, ours only to pin.

Git submodules, all under test/external/, checked out on demand: yarn setup doesn't fetch them, and each CI job fetches only its own, one commit deep.

git submodule update --init --recursive --depth 1   # check out the commits the repo pins
git submodule update --init --recursive --remote --depth 1 # move every pin to its upstream tip

Keep --depth 1 (wpt alone is ~161k files). --remote changes the recorded commits, so git status shows the paths modified — commit that only once CI is green on them, or git submodule update back to the pins.

One upstream corpus is vendored rather than pinned as a submodule:

  • test/fixtures/acorn-corpus.json — acorn's test suite — the one upstream corpus vendored rather than pinned, because acorn's npm tarball ships no tests. unitCases/javascript/parser.unittest.js holds both webpack parser entry points to it and owns recording it (no generator script or package.json entry): it replays acorn's test/tests*.js against a recording driver, keeping sources and options but never expected trees, which come from acorn itself. Bumping the acorn devDependency moves the corpus; to refresh, clone acorn at the new version into node_modules/.cache/acorn-<version> and re-run with WEBPACK_UPDATE_ACORN_CORPUS=1. With that checkout present the run checks the vendored corpus against it; without it (CI, most machines) the corpus stands on the version it names, which the run pins to the installed acorn.

Running one integration case

Run one integration case by name (<category> <case-name>, e.g. css basic):

yarn test:basic --testPathPatterns="ConfigTestCases" --testNamePattern="<category> <case>"

Swap in StatsTestCases, HotTestCases, WatchTestCases, … (full matrix in below). Prefix WEBPACK_TEST_STATS=1 to also write each build's verbose stats.txt (stats.<step>.txt for watch cases) next to its output under test/js/; it's off by default because it costs about as much as the build. The test262, html5lib, syntax-equivalence and css-parsing suites need submodules — run git submodule update --init --depth 1 test/external/test262-cases test/external/html5lib-tests test/external/wpt test/external/css-parsing-tests first, or they fail confusingly.

A configCases/ case is a mini project: index.js (assertions; a throw fails) plus webpack.config.js; the emitted bundle is executed, so it must run. Optional: errors.js / warnings.js export matcher arrays for expected diagnostics (otherwise any error/warning fails the case); test.filter.js returns false to skip (e.g. by Node version when the fixture itself needs newer syntax — see Target the Node baseline); test.config.js customizes the run (e.g. findBundle). Put DOM changes such as a server-rendered <link> in setupDocument(document, { options, index, target }), which runs once per run before any bundle executes, never in moduleScope, which runs again for every module and so repeats them.

How to Run Tests

More scripts

Every command is a package.json script; AGENTS.md lists the few whose use isn't obvious. The rest:

  • yarn setup — Install dependencies and link the checkout as webpack; non-interactive off a TTY.
  • yarn tsc — Type check the lib/ JSDoc.
  • yarn validate:changeset — Validate pending .changeset/ files.
  • yarn test:unit — All *.unittest.js.
  • yarn test:integration — Integration suites (basictest/longtest/test).
  • yarn test:test262 / test:html5lib / test:css-parsing / test:xmlconf — Spec-conformance suites.
  • yarn test:minify-corpora — webpack's one-pass JS minifier vs the published one it replaces, run for run and size for size, over every JS corpus (details).
  • yarn test:syntax-equivalence — HTML/CSS printers vs a real browser's reading of their output (configCases, wpt).
  • yarn test:size — Generated-code size over all configCases/ (per asset, plus runtime modules per runtime).
  • yarn cover:unit — Unit-test coverage.
  • yarn types:cover — Share of lib/ that is precisely typed.
  • yarn build:examples — Build examples/ (verify after changing options).

To execute all tests:

yarn test

Choose test command based on modified directory:

Modified directory/file Command
test/unitCases/**/*.unittest.js yarn test:base --testPathPatterns="<filename>"
test/specCases/ Run the matching yarn test:<suite> command
test/cases/ yarn test:basic
test/configCases/ yarn test:basic --testPathPatterns="ConfigTestCases"
test/statsCases/ yarn test:basic --testPathPatterns="StatsTestCases"
test/watchCases/ yarn test:base --testPathPatterns="WatchTestCases"
test/hotCases/ yarn test:base --testPathPatterns="HotTestCases"
test/benchmarkCases/ FILTER="<case-name>" yarn benchmark
lib/runtime/ yarn test:size (size of the generated code; --filter "<category>/" narrows it)
test/external/test262-cases/ yarn test:test262 (requires git submodule update --init test/external/test262-cases first)
test/external/html5lib-tests/ yarn test:html5lib (requires git submodule update --init --depth 1 test/external/html5lib-tests test/external/wpt first)
test/external/wpt/ yarn test:html5lib + yarn test:syntax-equivalence (require git submodule update --init --depth 1 test/external/html5lib-tests test/external/wpt first)
test/external/css-parsing-tests/ yarn test:css-parsing (requires git submodule update --init test/external/css-parsing-tests first)
test/external/xml-conformance-suite/ yarn test:xmlconf (requires git submodule update --init --depth 1 test/external/xml-conformance-suite first; without it the suite passes as a no-op)

Running a single test case with --testNamePattern. The test name format is <category> <case-name> (e.g., css basic, asset url):

yarn test:basic --testPathPatterns="ConfigTestCases" --testNamePattern="css basic"

Multiple patterns can be combined with |:

yarn test:basic --testPathPatterns="ConfigTestCases" --testNamePattern="css basic|css url"

Contribution Guide

  • Add new test cases in the appropriate folder.
  • Use Jest assertions and mocks for consistency.
  • Run yarn test before pushing changes to validate functionality.