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.
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.
- Purpose: Stores Jest snapshot files for comparing output consistency over time.
- Usage: Used for testing UI components, serialized data, or expected module outputs.
- 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/) — awebpack.config.mjsplus an entry; measures one build per scenario (mode-development,mode-development-rebuild,mode-production). *-unit(e.g.js-parser-unit/) — anindex.bench.mjsexportingdefault (bench) => {…}; measures a piece oflib/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; theexectask then instantiates the output (runtime bootstrap plus every module factory that runs at import time) and calls the entry's exportedrunon 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 withFILTER. Therealistic-appsizes are small (realistic-app/, 48 components),realistic-app-medium-local/(1,000),realistic-app-large-local/(5,000) andrealistic-app-very-large-local/(20,000).
- build (default, e.g.
- Writing a
*-runtimecase: the entry must exportrun(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 forcestarget: "node"and acommonjs2library so the output can be instantiated in-process; generate large fixtures fromoptions.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.
- Purpose: General test cases covering core functionalities.
- Usage: Includes unit and integration tests for various modules and features.
- 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/andhtml/minify-html/each run every directory inside them as one case, throughhelpers/mergedConfigCases.js. A directory keeps its ownwebpack.config.js,test.config.js(afterExecute,findBundleandmoduleScopeonly) andtest.filter.js, and builds into an output directory of its own. Itsittitles open with its name. A case needing another hook,errors.js,warnings.jsorinfrastructure-log.jsstays on its own. Each directory's inputs are copied as syntax fixtures too (below).
- 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.
- 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 thefn-namecases a renamed binding changes, keeps function and class names, and turnspure_getters,pure_conversionsandpure_heritageoff, 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 itsMINIFIED_FAILUREStable, and a listed case that passes fails the suite until removed. Andtest/specCases/minify-corpora.spectest.js, which minifies each test with webpack's printer and with terser.
- 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.
- Purpose: web-platform-tests, read two ways.
html/syntax/parsing/resources/*.datis the HTML tree-construction conformance corpus forparseHtml(html5lib-tests dropped its copy in224991e). The.htmldocuments underhtml/,conformance-checkers/anddom/nodes, plus the declarations thecss/**/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 readstest/external/html5lib-tests— initialize both to run the whole suite — andtest/specCases/syntaxEquivalence.spectest.js(yarn test:syntax-equivalence), whose browser tiers need a Chrome (CHROME_EXECUTABLE_PATHpicks 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.
- 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.
- 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.
- Purpose: swc's repository, read only under
crates/swc_ecma_minifier/tests: its fixtures with their configs, the testsexec.rsandmangle.rswrite inline, and the libraries it measures itself on. Each is held to terser's bytes like the terser corpora; a test with anexpected.stdout, and everyexec.rstest, also has its outputs run, and webpack's output may be no bigger than each fixture's recordedoutput.js, nor than what swc's port of a terser case records when itspassing.txtlists it, unlessSWC_SMALLERlists 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).
- Purpose: oxc's repository, read only under
crates/oxc_minifier/tests: the source eachtest…(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 byoxc-minify: webpack's output may be no bigger than oxc's unlessOXC_SMALLERlists 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 installedoxc-minifydisagree.
- Purpose: terser's own repository. Its
test/compresscases andtest/inputfiles are two of the seven corporalib/javascript/syntax-printer.jsis held to (test262, swc's fixtures,exec.rsandmangle.rstests, 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'scorrectphase fixes. A case stating itsexpect_stdoutalso has each output run in terser's sandbox, which must print it — or, forexpect_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 installedterserdisagree, so bumping the dependency means moving the pin with it. A new corpus is one entry in itsCORPORAlist.
- 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 tounitCases/<lang>/invariants.unittest.js, which snapshots its tokens, parse, errors and prints, and holds it to the relations inhelpers/syntaxInvariants/:spans,slicesandpurityfor the parser, each cut short inside a construct held tospansandslicesas well (reported ascut spansandcut slices); idempotence (cuts included), respellings,noticesandmeaningfor the printer;behaviorfor JavaScript, with a compressing preset's output held to a second pass (idempotenceunder mangling, andresidue), asyarn test:invariants:jsholds the corpus; andscalingfor a fixture built at a size.noticesasks that the comments a minifier must keep survive (CSS and JavaScript legal notices, HTML conditional comments, server-side includes and<?…?>);meaningthat the output reparses to what its source says (HTML and XML under every preset, CSS underbeautify, 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@licenseor@preserve), and a compressing JavaScript preset owes only the banner's. Each CSS fixture is also held toagreementwith css-tree. Which relation holds where, and why: COMPARE_TOOLS.md. JavaScript's per-fixture tests live inhelpers/javascriptInvariants.jsand run split acrossunitCases/javascript/invariants-shard-<n>.unittest.jsby fixture name, so Jest runs them on parallel workers;purityandscalingstay ininvariants.unittest.js, as they read every fixture together. Beside it, read byhelpers/fixture.js:options.json— print option sets. In JavaScript,"behavior": trueon 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 ofRENDER_WIDTHS, and every element's boxes, itsstyleattribute 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 thesyntax-equivalencesuite'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 pastSVG_CHANNEL_TOLERANCEcounting; 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 aSourceProcessorset, and itsexpected.jsonentries answer for the marked sets alone."renderEmbeddedSource": "<name>"(or{ "name", "options"?, "async"? },asyncanswering through a Promise) picks a renderer fromhelpers/embeddedRenderers.js, and{ "regexp": "<source>", "flags"?: "<flags>" }stands for a RegExp anywhere in a set. Three keys send a set throughreadPrint:"print": "<name>"picks the printer:process(the default),processAsyncor the language's minimizer (cssMinify,htmlMinify,xmlMinify,jsMinify)."visit"takes a visit spec (below) and fires its visitors during aprocessorprocessAsyncprint."minimizer": { "extractComments"?, "sourceMap"?, "buffer"?, "asset"? }sets the minimizer's other arguments: itsextractCommentsargument, an input source map read from a file in the fixture's directory, aBufferasset, 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, underminimizer, so an absent list differs from an empty one; otherwise only the non-empty warnings, errors and extracted comments. Thevisitlog and a recording renderer's offers come last.
parse.json— extra calls, each{ "entry"?, "options"?, "visit"?, "pos"?, "fields"? }. Each runner'sENTRIESlists the entry names; an unknown name or key, or a key the entry does not take, throws.entryis the public entry point by name; the document parse where absent.optionsare its JSON options. A CSSskip.typeslistsNodeTypenames, whichbuildSkipSetturns into the skip set.posis the offset to start reading at."visit": truelogs the entry's callbacks as one more snapshot entry.fieldslogs reads made throughAon every node the entry returns, as one more entry.- On
SourceProcessor,"visit"takes a visit spec instead:{ "types"?, "fields"?, "exit"?, "at"? }. It names theNodeTypes to visit, the reads to log on each enter, and whether exits are logged.atlists actions, each{ "type", "on"?, "name"?, "source"? (a prefix), "index"?, "do", "with"? }, wheredoisskipChildren,stop,removeorreplace(withis the text). - A read is
name,value,source,range,locorchildCount; on a path alsoindexorparent; orflag:<Flag>,fieldCount:<Field>, orrangeOf,startOf,endOf,textOforsourceOffollowed by:<Part>.
expected.json— known differences the invariants may report, each{ "relation", "contains", "presets"?, "why" }: a finding of that relation whose repro holdscontains, under one ofpresets(every preset where absent). An entry no finding needs fails as stale. A known bug'swhyopens withknown bug:. In JavaScript, abehaviorentry withoutpresetsanswers for the setsoptions.jsonmarks; one namingformatorbeautifyfor 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 noindex.<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.lengthsays the fixture scales), also builds the input at sizen;source()passesundefinedfor the size the snapshots hold. One test per runner holds every such fixture toscaling: it minifies the input at 64 and 128 under the first preset and counts, with V8's precise block coverage, how often each block oflib/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 withjest.isolateModules. Anexpected.jsonentry 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 inoptions.jsonorparse.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 onSourceProcessor, 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 acheck.
- Size budget: a source longer than
INVARIANT_BUDGET(20,000 characters, inhelpers/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 ownNot enough stack spacerefusal or parse error) snapshotsoverflows the stack, never the offset or the engine's wording, and the source is held to no relation. - TypeScript fixtures:
fixtures/typescript/<name>/index.tsis one input tounitCases/typescript/node-type-stripping.unittest.js, which snapshots the treeparseProgramreads withtypescript: trueand compares it with the tree of Node.js'smodule.stripTypeScriptTypesoutput read as JavaScript (where Node.js has that API); where Node.js refuses the source, the parse must refuse it too, withunsupported-typescript-syntaxexactly where Node.js says the syntax is not supported. Anexpected.jsonentry{ "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 aslib/typescript/blankTypeScript.jsblanks 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 underfixtures/json/<name>/index.json, which no invariants runner reads.yarn lint:syntax-test-inputs(part ofyarn 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…ofrows (destructured too),Object.entries/values/keystables and computed lookups. It has no escape hatch: what a test expects, the arguments of string helpers such asescapeText, a preparsed tree and whatfsorpathreturn are not sources; an input built at a size goes in afixture.jssource(). - Fuzzing:
unitCases/<lang>/fuzz.unittest.jsjoins 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; theFuzzworkflow 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 withFUZZ_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'sknownlist with itswhy.
- Purpose: What runs the suites, as opposed to what they test. Jest's lifecycle (
globalSetup.js,globalTeardown.js,setupTestFramework.js), thepatch-node-env.jstest environment,runtimeCrashReporter.js, the caserunner/, thesnapshot/resolver and matchers,benchmark/, andruntimes/. runtimes/: The preload and setup files that let jest run under a non-Node runtime —bun-preload.jsandbun-sandbox-setup.jsforyarn test:bun,deno-worker-setup.jsanddeno-import-map.jsonforyarn test:deno. Wired in throughjest.config.jsand thetest:base:bun/test:base:denoscripts.- Not helpers: a reusable assertion or fixture belongs in
helpers/;harness/is only for machinery the test runner itself loads.
- Purpose: Utility functions and scripts to assist in testing.
- Usage: Provides reusable functions for mock data generation, cleanup, and assertions.
- 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,requireonnode,importScriptsonwebworker) and a twin underhotCases/esm-output/withoutput.module: trueandchunkFormat: "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 needspublicPath: "auto": a Node ES module worker can't import the harness'shttps://default.
- 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.jsruns every<group>/<case>/holding atest.config.js, from Node.js 22.15 up. A case has awebpack.config.js(the runner setscontext,output.pathand the dev server plugin), its sources and atest.config.jswithdevServeroptions, apageserved at/(left out, the runner's default page loads/main.js;page: undefinedserves the build's ownindex.html), andsteps. The first step loads the page; each later one writes itseditand waits until the page shows itsexpectchecks (an element's text or a computed style) and the erroroverlay.update: "hot"or"reload"says how the page took the edit, read from a marker onwindowthat survives an in-place update but not a reload. A timeout quotes what the page logged;devServer: { client: { logging: "verbose" } }makes that tell more.
- 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 deferand an async chunk, plus a panel driving the HMR API itself (data/dispose,addStatusHandler,check,invalidate). Nothing here runs in CI. - Usage:
yarn playgroundserves it onhttp://localhost:8080with hot reloading on; edit any file and watch the page. Seetest/hotPlayground/README.mdfor what each file demonstrates.
- Purpose: Contains test cases related to memory limits.
- Usage: Ensures Webpack doesn’t exceed memory constraints.
- 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, anoptions.mjswhose exportedsetup()runs first to generate or install its sources (intogenerated/, which git ignores). The harness sets onlycontext,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-5kandreact-1k-esm, React apps of that many components (lazy routes, CSS modules, JSON, SVG) from therealistic-appbenchmark's generator (test/harness/benchmark/create-app.mjs).node:node-ssrandnode-ssr-esm, that app rendered on the server by anhttpserver withreact-dom/server(test/harness/size/create-server.mjs).webworker:webworkerandwebworker-esm, a message loop lazily loading 40 data tasks built onlodash-esanddate-fns(test/harness/size/create-worker.mjs).library: one small library built once peroutput.library.type, the types read from the schema.
- 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 doestest262-parser.spectest.js—yarn test:test262-parserhtml5lib.spectest.js—yarn test:html5libsyntaxEquivalence.spectest.js—yarn test:syntax-equivalencecssParsing-webpack.spectest.js—yarn test:css-parsingxmlconf.spectest.js—yarn test:xmlconfminify-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 unmetjs-fuzz.spectest.js—yarn test:js-fuzz: programs fromtest/helpers/jsFuzzProgram.js, in the sloppy ES5 terser's ufuzz writes, in modern syntax, as modules importing a fixeddepand 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=randomruns a new one named in the test's title,JS_FUZZ_PROGRAMSsets the programs per seed, andJS_FUZZ_RANDOM_OPTION_SETSsets how many random minifier option sets each generated program runs under.xml-fuzz.spectest.js—yarn test:xml-fuzz: XML documents fromtest/helpers/xmlFuzzDocument.js, with XML declarations, DOCTYPE declarations, namespaces, comments, processing instructions, CDATA, references and deeply nested elements. Each generated document is held totest/helpers/syntaxInvariants/xml.js, including idempotence by default; setXML_FUZZ_CHECK_IDEMPOTENCE=0to disable idempotence checks.XML_FUZZ_SEED=<n>replays one seed,XML_FUZZ_SEED=randomruns a new one named in the test's title, andXML_FUZZ_INPUTSsets the inputs per seed.syntax-fuzz.spectest.js—yarn test:syntax-fuzz, which CI does not run: stylesheets fromtest/helpers/cssFuzzStylesheet.js, built from mdn-data's property, at-rule, descriptor and selector grammars, and documents fromtest/helpers/htmlFuzzDocument.js, built from webref's element lists and the attribute tables inlib/html/data.js, with those stylesheets in<style>andstyle="". Each input is held to the syntax invariants and, in the ChromelaunchBrowserstarts, 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 spelledaand digits0where it still breaks, and reported. Each open defect is asyntax-fuzz-*fixture whoseexpected.jsonfiles 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=1writes 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 HTMLsyntax-tokenizer.js,syntax-parser.jsandsyntax-printer.jsno generated input reached, and fails where a count moved fromsyntax-fuzz.unreached.json: up, extend a generator to reach the new code; down, re-record withSYNTAX_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=randomruns a new one named in the test's title, andSYNTAX_FUZZ_INPUTSsets the inputs per seed; any of them skips the coverage test.
- Purpose: Tests focused on Webpack’s statistical outputs.
- Usage: Verifies correct bundle sizes, dependencies, and optimizations.
- Purpose: The suite drivers —
TestCases.js,ConfigTestCases.js,HotTestCases.js,WatchTestCases.js— each exportingdescribeCases(config). - Usage: The
*.test.js/*.basictest.js/*.longtest.jsfiles at the top oftest/are thin shims that calldescribeCaseswith 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.jsholds the option sets theTestCases*andHotTestCases*shims run under, re-exported from each driver asvariants. 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 sharedtest/root viatestRootDirectory(path.join(__dirname, "..")), never against__dirname.
- Purpose: Type-checking tests, likely for TypeScript integration.
- Usage: Ensures proper type definitions and compliance.
- Purpose: Contains
*.unittest.jsunit 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/andhtml/(tokenizer,parser,printer),xml/(printer) andjson/(printer,web-manifest). A printer's file holds both of its modes and the language's minifier, which drives the printer in itsminifymode. The tests of thetooling/scripts sit intooling/. The rest, webpack's own classes such asJavascriptParser, stay at the top level.
- Purpose: Tests for Webpack’s watch mode functionality.
- Usage: Ensures file changes trigger correct rebuild behavior.
- 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:sizebuilds everyconfigCases/case, plus every application insizeCoreReports/(reported asapps/<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 onemainlast 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 fromFILTER/NEGATIVE_FILTER). - Note: the cases are built with the defaults a user gets — minification on, no
output.pathinfo— not with theConfigTestCasesones. Needs Node.js >= 22.15 for zstd.
- Purpose: Tests Webpack’s
BannerPluginfunctionality. - Usage: Ensures that the plugin correctly adds banners to the bundled files.
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).
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.
- 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.
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.
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.
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: trueintest.config.jsremoves 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.
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__.ereaches is a finding, unless the build recorded why it kept the runtime form —performance.analyzableBailoutsreads the same reasons — or anevaldevtool 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.
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.
test/external/test262-cases— tc39/test262; fetched bytest262,spectest/external/html5lib-tests— html5lib/html5lib-tests; fetched byspectest/external/wpt— web-platform-tests/wpt; fetched byspec,syntax-equivalence(browsers)test/external/css-parsing-tests— CourtBouillon/css-parsing-tests; fetched byspectest/external/xml-conformance-suite— lddubeau/xml-conformance-suite (the W3C XML Conformance Test Suite); fetched byspectest/external/terser— terser/terser, pinned to the installedterser's version; fetched byspectest/external/swc— swc-project/swc, read only undercrates/swc_ecma_minifier/tests; fetched byspectest/external/oxc— oxc-project/oxc, pinned to the installedoxc-minify's release and read only undercrates/oxc_minifier/tests; fetched byspec
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 tipKeep --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.jsholds both webpack parser entry points to it and owns recording it (no generator script orpackage.jsonentry): it replays acorn'stest/tests*.jsagainst a recording driver, keeping sources and options but never expected trees, which come from acorn itself. Bumping theacorndevDependency moves the corpus; to refresh, clone acorn at the new version intonode_modules/.cache/acorn-<version>and re-run withWEBPACK_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.
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.
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 aswebpack; non-interactive off a TTY.yarn tsc— Type check thelib/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 allconfigCases/(per asset, plus runtime modules per runtime).yarn cover:unit— Unit-test coverage.yarn types:cover— Share oflib/that is precisely typed.yarn build:examples— Buildexamples/(verify after changing options).
To execute all tests:
yarn testChoose 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"- Add new test cases in the appropriate folder.
- Use Jest assertions and mocks for consistency.
- Run
yarn testbefore pushing changes to validate functionality.