Webpack from Nothing

Unit Testing

Unit testing has always been possible in JavaScript, but early test runners required opening a page in a web browser that executed the tests. Because of Node, we now can execute JavaScript on the command-line, without a browser, and this is how we'd like to work, because it's faster and easier to automate (e.g. in a continuous integration systems).

Spoiler: we don't get to work this way.

We can get close, by executing our tests in PhantomJS, a headless version of WebKit.

Ideally, we want the ability to:

There are many JavaScript testing frameworks, though even the definition of what a testing framework is is unclear. According to the State of JavaScript 2018 testing results, Jest and Mocha are the top contenders for most popular. We'll go with [Jest][jest] since it just eeks out Mocha and has higher growth, so likely to be a solid contender.

First, we'll add it to our package.json. We'll use yarn add again.

> yarn add -D jest
yarn add v1.13.0
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 178 new dependencies.
info Direct dependencies
└─ jest@24.5.0
info All dependencies
├─ @babel/generator@7.4.0
├─ @babel/helper-function-name@7.1.0
├─ @babel/helper-get-function-arity@7.0.0
├─ @babel/helper-plugin-utils@7.0.0
├─ @babel/helper-split-export-declaration@7.4.0
├─ @babel/helpers@7.4.2
├─ @babel/highlight@7.0.0
├─ @babel/plugin-syntax-object-rest-spread@7.2.0
├─ @babel/template@7.4.0
├─ @babel/traverse@7.4.0
├─ @cnakazawa/watch@1.0.3
├─ @jest/core@24.5.0
├─ @jest/reporters@24.5.0
├─ @types/babel__core@7.1.0
├─ @types/babel__generator@7.0.2
├─ @types/babel__template@7.0.2
├─ @types/babel__traverse@7.0.6
├─ @types/stack-utils@1.0.1
├─ acorn-globals@4.3.0
├─ acorn-walk@6.1.1
├─ ansi-regex@4.1.0
├─ append-transform@1.0.0
├─ argparse@1.0.10
├─ arrify@1.0.1
├─ asn1@0.2.4
├─ astral-regex@1.0.0
├─ async@2.6.2
├─ asynckit@0.4.0
├─ aws-sign2@0.7.0
├─ aws4@1.8.0
├─ babel-jest@24.5.0
├─ babel-plugin-jest-hoist@24.3.0
├─ babel-preset-jest@24.3.0
├─ bcrypt-pbkdf@1.0.2
├─ browser-process-hrtime@0.1.3
├─ browser-resolve@1.11.3
├─ bser@2.0.0
├─ capture-exit@2.0.0
├─ caseless@0.12.0
├─ ci-info@2.0.0
├─ co@4.6.0
├─ combined-stream@1.0.7
├─ compare-versions@3.4.0
├─ convert-source-map@1.6.0
├─ cssom@0.3.6
├─ cssstyle@1.2.2
├─ dashdash@1.14.1
├─ data-urls@1.1.0
├─ deep-is@0.1.3
├─ default-require-extensions@2.0.0
├─ delayed-stream@1.0.0
├─ detect-newline@2.1.0
├─ diff-sequences@24.3.0
├─ ecc-jsbn@0.1.2
├─ error-ex@1.3.2
├─ es-abstract@1.13.0
├─ es-to-primitive@1.2.0
├─ escodegen@1.11.1
├─ esprima@3.1.3
├─ extend@3.0.2
├─ extsprintf@1.3.0
├─ fast-levenshtein@2.0.6
├─ fileset@2.0.3
├─ forever-agent@0.6.1
├─ form-data@2.3.3
├─ getpass@0.1.7
├─ globals@11.11.0
├─ growly@1.3.0
├─ handlebars@4.1.1
├─ har-schema@2.0.0
├─ har-validator@5.1.3
├─ has-symbols@1.0.0
├─ has@1.0.3
├─ hosted-git-info@2.7.1
├─ http-signature@1.2.0
├─ invariant@2.2.4
├─ is-arrayish@0.2.1
├─ is-date-object@1.0.1
├─ is-generator-fn@2.0.0
├─ is-regex@1.0.4
├─ is-symbol@1.0.2
├─ is-typedarray@1.0.0
├─ is-wsl@1.1.0
├─ isstream@0.1.2
├─ istanbul-api@2.1.1
├─ istanbul-lib-hook@2.0.3
├─ istanbul-lib-instrument@3.1.0
├─ istanbul-lib-report@2.0.4
├─ istanbul-lib-source-maps@3.0.2
├─ istanbul-reports@2.1.1
├─ jest-changed-files@24.5.0
├─ jest-cli@24.5.0
├─ jest-docblock@24.3.0
├─ jest-each@24.5.0
├─ jest-environment-jsdom@24.5.0
├─ jest-environment-node@24.5.0
├─ jest-leak-detector@24.5.0
├─ jest-pnp-resolver@1.2.1
├─ jest-resolve-dependencies@24.5.0
├─ jest-runner@24.5.0
├─ jest-serializer@24.4.0
├─ jest-watcher@24.5.0
├─ jest@24.5.0
├─ js-tokens@4.0.0
├─ js-yaml@3.13.0
├─ jsdom@11.12.0
├─ jsesc@2.5.2
├─ json-schema@0.2.3
├─ json-stringify-safe@5.0.1
├─ jsprim@1.4.1
├─ kleur@3.0.2
├─ left-pad@1.3.0
├─ leven@2.1.0
├─ levn@0.3.0
├─ load-json-file@4.0.0
├─ loose-envify@1.4.0
├─ makeerror@1.0.11
├─ merge-stream@1.0.1
├─ mime-db@1.38.0
├─ mime-types@2.1.22
├─ natural-compare@1.4.0
├─ node-int64@0.4.0
├─ node-modules-regexp@1.0.0
├─ node-notifier@5.4.0
├─ normalize-package-data@2.5.0
├─ nwsapi@2.1.2
├─ oauth-sign@0.9.0
├─ object.getownpropertydescriptors@2.0.3
├─ optimist@0.6.1
├─ optionator@0.8.2
├─ p-each-series@1.0.0
├─ p-reduce@1.0.0
├─ parse-json@4.0.0
├─ parse5@4.0.0
├─ path-parse@1.0.6
├─ path-type@3.0.0
├─ performance-now@2.1.0
├─ pirates@4.0.1
├─ prompts@2.0.4
├─ psl@1.1.31
├─ qs@6.5.2
├─ react-is@16.8.6
├─ read-pkg-up@4.0.0
├─ read-pkg@3.0.0
├─ request-promise-core@1.1.2
├─ request@2.88.0
├─ resolve@1.10.0
├─ rsvp@4.8.4
├─ sane@4.1.0
├─ saxes@3.1.9
├─ shellwords@0.1.1
├─ sisteransi@1.0.0
├─ spdx-correct@3.1.0
├─ spdx-exceptions@2.2.0
├─ sprintf-js@1.0.3
├─ sshpk@1.16.1
├─ stack-utils@1.0.2
├─ stealthy-require@1.1.1
├─ test-exclude@5.1.0
├─ tmpl@1.0.4
├─ to-fast-properties@2.0.0
├─ tough-cookie@2.5.0
├─ trim-right@1.0.1
├─ tunnel-agent@0.6.0
├─ tweetnacl@0.14.5
├─ uglify-js@3.5.2
├─ util.promisify@1.0.0
├─ uuid@3.3.2
├─ validate-npm-package-license@3.0.4
├─ verror@1.10.0
├─ w3c-xmlserializer@1.1.2
├─ walker@1.0.7
├─ whatwg-encoding@1.0.5
├─ whatwg-mimetype@2.3.0
├─ wordwrap@1.0.0
├─ write-file-atomic@2.4.1
├─ ws@5.2.2
└─ xmlchars@1.3.1
Done in 8.80s.
warning "jest > jest-cli > jest-config > jest-resolve@24.5.0" has unmet peer dependency "jest-haste-map@^24.0.0".
warning "jest > jest-cli > @jest/core > jest-resolve-dependencies@24.5.0" has unmet peer dependency "jest-resolve@^24.1.0".

This will install Jest which includes the command-line app jest:

> $(yarn bin)/jest -h
Usage: jest [--config=<pathToConfigFile>] [TestPathPattern]

Options:
  --help, -h                    Show help                              [boolean]
  --version, -v                 Print the version and exit             [boolean]
  --all                         The opposite of `onlyChanged`. If `onlyChanged`
                                is set by default, running jest with `--all`
                                will force Jest to run all tests instead of
                                running only tests related to changed files.
  --automock                    Automock all files by default.         [boolean]
  --bail, -b                    Exit the test suite immediately after `n` number
                                of failing tests.
  --browser                     Respect the "browser" field in package.json when
                                resolving modules. Some packages export
                                different versions based on whether they are
                                operating in node.js or a browser.     [boolean]
  --cache                       Whether to use the transform cache. Disable the
                                cache using --no-cache.                [boolean]
  --cacheDirectory              The directory where Jest should store its cached
                                dependency information.                 [string]
  --changedFilesWithAncestor    Runs tests related to the current changes and
                                the changes made in the last commit. Behaves
                                similarly to `--onlyChanged`.          [boolean]
  --changedSince                Runs tests related to the changes since the
                                provided branch. If the current branch has
                                diverged from the given branch, then only
                                changes made locally will be tested. Behaves
                                similarly to `--onlyChanged`.           [string]
  --ci                          Whether to run Jest in continuous integration
                                (CI) mode. This option is on by default in most
                                popular CI environments. It will  prevent
                                snapshots from being written unless explicitly
                                requested.            [boolean] [default: false]
  --clearCache                  Clears the configured Jest cache directory and
                                then exits. Default directory can be found by
                                calling jest --showConfig              [boolean]
  --clearMocks                  Automatically clear mock calls and instances
                                between every test. Equivalent to calling
                                jest.clearAllMocks() between each test.[boolean]
  --collectCoverage             Alias for --coverage.                  [boolean]
  --collectCoverageFrom         A glob pattern relative to <rootDir> matching
                                the files that coverage info needs to be
                                collected from.                         [string]
  --collectCoverageOnlyFrom     Explicit list of paths coverage will be
                                restricted to.                           [array]
  --color                       Forces test results output color highlighting
                                (even if stdout is not a TTY). Set to false if
                                you would like to have no colors.      [boolean]
  --colors                      Alias for `--color`.                   [boolean]
  --config, -c                  The path to a jest config file specifying how to
                                find and execute tests. If no rootDir is set in
                                the config, the directory containing the config
                                file is assumed to be the rootDir for the
                                project.This can also be a JSON encoded value
                                which Jest will use as configuration.   [string]
  --coverage                    Indicates that test coverage information should
                                be collected and reported in the output.
                                                                       [boolean]
  --coverageDirectory           The directory where Jest should output its
                                coverage files.                         [string]
  --coveragePathIgnorePatterns  An array of regexp pattern strings that are
                                matched against all file paths before executing
                                the test. If the file pathmatches any of the
                                patterns, coverage information will be skipped.
                                                                         [array]
  --coverageReporters           A list of reporter names that Jest uses when
                                writing coverage reports. Any istanbul reporter
                                can be used.                             [array]
  --coverageThreshold           A JSON string with which will be used to
                                configure minimum threshold enforcement for
                                coverage results                        [string]
  --debug                       Print debugging info about your jest config.
                                                                       [boolean]
  --detectLeaks                 **EXPERIMENTAL**: Detect memory leaks in tests.
                                After executing a test, it will try to garbage
                                collect the global object used, and fail if it
                                was leaked            [boolean] [default: false]
  --detectOpenHandles           Print out remaining open handles preventing Jest
                                from exiting at the end of a test run.
                                                      [boolean] [default: false]
  --env                         The test environment used for all tests. This
                                can point to any file or node module. Examples:
                                `jsdom`, `node` or `path/to/my-environment.js`
                                                                        [string]
  --errorOnDeprecated           Make calling deprecated APIs throw helpful error
                                messages.             [boolean] [default: false]
  --expand, -e                  Use this flag to show full diffs instead of a
                                patch.                                 [boolean]
  --filter                      Path to a module exporting a filtering function.
                                This method receives a list of tests which can
                                be manipulated to exclude tests from running.
                                Especially useful when used in conjunction with
                                a testing infrastructure to filter known broken
                                tests.                                  [string]
  --findRelatedTests            Find related tests for a list of source files
                                that were passed in as arguments. Useful for
                                pre-commit hook integration to run the minimal
                                amount of tests necessary.             [boolean]
  --forceExit                   Force Jest to exit after all tests have
                                completed running. This is useful when resources
                                set up by test code cannot be adequately cleaned
                                up.                                    [boolean]
  --globalSetup                 The path to a module that runs before All Tests.
                                                                        [string]
  --globalTeardown              The path to a module that runs after All Tests.
                                                                        [string]
  --globals                     A JSON string with map of global variables that
                                need to be available in all test environments.
                                                                        [string]
  --haste                       A JSON string with map of variables for the
                                haste module system                     [string]
  --init                        Generate a basic configuration file    [boolean]
  --json                        Prints the test results in JSON. This mode will
                                send all other test output and user messages to
                                stderr.                                [boolean]
  --lastCommit                  Run all tests affected by file changes in the
                                last commit made. Behaves similarly to
                                `--onlyChanged`.                       [boolean]
  --listTests                   Lists all tests Jest will run given the
                                arguments and exits. Most useful in a CI system
                                together with `--findRelatedTests` to determine
                                the tests Jest will run based on specific files
                                                      [boolean] [default: false]
  --logHeapUsage                Logs the heap usage after every test. Useful to
                                debug memory leaks. Use together with
                                `--runInBand` and `--expose-gc` in node.
                                                                       [boolean]
  --mapCoverage                 Maps code coverage reports against original
                                source code when transformers supply source
                                maps.

                                DEPRECATED                             [boolean]
  --maxConcurrency              Specifies the maximum number of tests that are
                                allowed to runconcurrently. This only affects
                                tests using `test.concurrent`.
                                                           [number] [default: 5]
  --maxWorkers, -w              Specifies the maximum number of workers the
                                worker-pool will spawn for running tests. This
                                defaults to the number of the cores available on
                                your machine. (its usually best not to override
                                this default)                           [number]
  --moduleDirectories           An array of directory names to be searched
                                recursively up from the requiring module's
                                location.                                [array]
  --moduleFileExtensions        An array of file extensions your modules use.
                                If you require modules without specifying a
                                file extension, these are the extensions Jest
                                will look for.                           [array]
  --moduleNameMapper            A JSON string with a map from regular
                                expressions to module names that allow to stub
                                out resources, like images or styles with a
                                single module                           [string]
  --modulePathIgnorePatterns    An array of regexp pattern strings that are
                                matched against all module paths before those
                                paths are to be considered "visible" to the
                                module loader.                           [array]
  --modulePaths                 An alternative API to setting the NODE_PATH env
                                variable, modulePaths is an array of absolute
                                paths to additional locations to search when
                                resolving modules.                       [array]
  --noStackTrace                Disables stack trace in test results output
                                                                       [boolean]
  --notify                      Activates notifications for test results.
                                                                       [boolean]
  --notifyMode                  Specifies when notifications will appear for
                                test results.
                                            [string] [default: "failure-change"]
  --onlyChanged, -o             Attempts to identify which tests to run based on
                                which files have changed in the current
                                repository. Only works if you're running tests
                                in a git or hg repository at the moment.
                                                                       [boolean]
  --onlyFailures, -f            Run tests that failed in the previous execution.
                                                                       [boolean]
  --outputFile                  Write test results to a file when the --json
                                option is also specified.               [string]
  --passWithNoTests             Will not fail if no tests are found (for example
                                while using `--testPathPattern`.)
                                                      [boolean] [default: false]
  --preset                      A preset that is used as a base for Jest's
                                configuration.                          [string]
  --prettierPath                The path to the "prettier" module used for
                                inline snapshots.                       [string]
  --projects                    A list of projects that use Jest to run all
                                tests of all projects in a single instance of
                                Jest.                                    [array]
  --reporters                   A list of custom reporters for the test suite.
                                                                         [array]
  --resetMocks                  Automatically reset mock state between every
                                test. Equivalent to calling jest.resetAllMocks()
                                between each test.                     [boolean]
  --resetModules                If enabled, the module registry for every test
                                file will be reset before running each
                                individual test.                       [boolean]
  --resolver                    A JSON string which allows the use of a custom
                                resolver.                               [string]
  --restoreMocks                Automatically restore mock state and
                                implementation between every test. Equivalent to
                                calling jest.restoreAllMocks() between each
                                test.                                  [boolean]
  --rootDir                     The root directory that Jest should scan for
                                tests and modules within.               [string]
  --roots                       A list of paths to directories that Jest should
                                use to search for files in.              [array]
  --runInBand, -i               Run all tests serially in the current process
                                (rather than creating a worker pool of child
                                processes that run tests). This is sometimes
                                useful for debugging, but such use cases are
                                pretty rare.                           [boolean]
  --runTestsByPath              Used when provided patterns are exact file
                                paths. This avoids converting them into a
                                regular expression and matching it against every
                                single file.          [boolean] [default: false]
  --runner                      Allows to use a custom runner instead of Jest's
                                default test runner.                    [string]
  --setupFiles                  A list of paths to modules that run some code
                                to configure or set up the testing environment
                                before each test.                        [array]
  --setupFilesAfterEnv          A list of paths to modules that run some code
                                to configure or set up the testing framework
                                before each test                         [array]
  --showConfig                  Print your jest config and then exits. [boolean]
  --silent                      Prevent tests from printing messages through the
                                console.                               [boolean]
  --skipFilter                  Disables the filter provided by --filter. Useful
                                for CI jobs, or local enforcement when fixing
                                tests.                                 [boolean]
  --snapshotSerializers         A list of paths to snapshot serializer modules
                                Jest should use for snapshot testing.    [array]
  --testEnvironment             Alias for --env                         [string]
  --testEnvironmentOptions      Test environment options that will be passed to
                                the testEnvironment. The relevant options depend
                                on the environment.                     [string]
  --testFailureExitCode         Exit code of `jest` command if the test run
                                failed                                  [string]
  --testLocationInResults       Add `location` information to the test results
                                                      [boolean] [default: false]
  --testMatch                   The glob patterns Jest uses to detect test
                                files.                                   [array]
  --testNamePattern, -t         Run only tests with a name that matches the
                                regex pattern.                          [string]
  --testPathIgnorePatterns      An array of regexp pattern strings that are
                                matched against all test paths before executing
                                the test. If the test path matches any of the
                                patterns, it will be skipped.            [array]
  --testPathPattern             A regexp pattern string that is matched against
                                all tests paths before executing the test.
                                                                         [array]
  --testRegex                   A string or array of string regexp patterns that
                                Jest uses to detect test files.          [array]
  --testResultsProcessor        Allows the use of a custom results processor.
                                This processor must be a node module that
                                exports a function expecting as the first
                                argument the result object.             [string]
  --testRunner                  Allows to specify a custom test runner. The
                                default is  `jasmine2`. A path to a custom test
                                runner can be provided:
                                `<rootDir>/path/to/testRunner.js`.      [string]
  --testURL                     This option sets the URL for the jsdom
                                environment.                            [string]
  --timers                      Setting this value to fake allows the use of
                                fake timers for functions such as setTimeout.
                                                                        [string]
  --transform                   A JSON string which maps from regular
                                expressions to paths to transformers.   [string]
  --transformIgnorePatterns     An array of regexp pattern strings that are
                                matched against all source file paths before
                                transformation.                          [array]
  --unmockedModulePathPatterns  An array of regexp pattern strings that are
                                matched against all modules before the module
                                loader will automatically return a mock for
                                them.                                    [array]
  --updateSnapshot, -u          Use this flag to re-record snapshots. Can be
                                used together with a test suite pattern or with
                                `--testNamePattern` to re-record snapshot for
                                test matching the pattern              [boolean]
  --useStderr                   Divert all output to stderr.           [boolean]
  --verbose                     Display individual test results with the test
                                suite hierarchy.                       [boolean]
  --watch                       Watch files for changes and rerun tests related
                                to changed files. If you want to re-run all
                                tests when a file has changed, use the
                                `--watchAll` option.                   [boolean]
  --watchAll                    Watch files for changes and rerun all tests. If
                                you want to re-run only the tests related to the
                                changed files, use the `--watch` option.
                                                                       [boolean]
  --watchPathIgnorePatterns     An array of regexp pattern strings that are
                                matched against all paths before trigger test
                                re-run in watch mode. If the test path matches
                                any of the patterns, it will be skipped. [array]
  --watchman                    Whether to use watchman for file crawling.
                                Disable using --no-watchman.           [boolean]

Documentation: https://jestjs.io/

Much to my surprise, Jest works on a minimal test with no setup. Let's see that by creating a basic test in test/canary.test.js:

describe("canary", function() {
  it("can run a test", function() {
    expect(true).toBe(true);
  });
});

Hopefully, Jest's syntax and API is clear, but the idea is that we use describe to block off a bunch of tests we'll write, and then it for each test. The idea is that these can be pieced together in some pidgen-like English that developers convince themselves is a specification. It's silly, but works.

And now we have a test:

> $(yarn bin)/jest test/
PASS test/canary.test.js
  canary
    ✓ can run a test (5ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.833s
Ran all test suites matching /test\//i.

This validates that we can run a test, but where is Webpack in all this? It's absence is felt if we try to access our code.

Let's modify our canary test to load our markdown previewer and assert that it's defined:

/* start new code */
import markdownPreviewer from "../js/markdownPreviewer"

/* end new code */
describe("canary", function() {
  it("can run a test", function() {
/* start new code */
    expect(markdownPreviewer).toBeDefined();
/* end new code */
  });
});

Now, when we run Jest again, we see the problem:

> $(yarn bin)/jest test/
FAIL test/canary.test.js
  ● Test suite failed to run

    /Users/davec/Projects/Personal/wtf-is-a-webpack/work/work/test/canary.test.js:2
    import markdownPreviewer from "../js/markdownPreviewer";
           ^^^^^^^^^^^^^^^^^

    SyntaxError: Unexpected identifier

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:451:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:493:19)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.28s
Ran all test suites matching /test\//i.

Jest doesn't understand import, since Jest is running via Node and Node doesn't understand import. While Node understands require, our code uses import, so using require in our test won't work. The entire reason we are using Webpack is to assemble our bundle of JavaScript code, so it stands to reason we need to use Webpack with our tests as well.

Let's create a second Webpack configuration that will produce a test-only bundle that we can feed to Jest. We'll place this in test/webpack.test.config.js:

const path = require('path');

module.exports = {
  entry: "./test/canary.test.js",
  output: {
    path: path.resolve(__dirname, "."),
    filename: "bundle.test.js"
  },
  mode: "none"
};

This is similar to our existing config with a few differences. First, our entry point is our test file instead of js/index.js. Second, our output goes to the test directory and uses bundle.test.js as the output name. None of this is required, but it helps immensely when we see files in our project to know what they are for without having to refer to configuration. It's pretty obvious that the file bundle.test.js is not for public consumption and that the file webpack.test.config.js is a Webpack configuration for testing.

Also, please note the very confusing file paths. Our entry point's path is relative to where we are running Webpack, but our output path is relative to where the Webpack configuration lives. I can't explain why this is, and it's very confusing, but just keep a note of it.

Let's run Webpack using this new configuration:

> $(yarn bin)/webpack --config test/webpack.test.config.js --display-error-details
Hash: 023f480a14bd7dbc1c90
Version: webpack 4.29.6
Time: 222ms
Built at: 2019-03-30 10:24:05
         Asset      Size  Chunks             Chunk Names
bundle.test.js  80.2 KiB       0  [emitted]  main
Entrypoint main = bundle.test.js
[0] ./test/canary.test.js 260 bytes {0} [built]
[1] ./js/markdownPreviewer.js 381 bytes {0} [built]
    + 6 hidden modules

We can see that produced the desired file:

> ls test/
bundle.test.js
canary.test.js
webpack.test.config.js

Now, we can run Jest, telling it to run the tests in the bundle, since that contains all of our tests:

> $(yarn bin)/jest test/bundle.test.js
PASS test/bundle.test.js
  canary
    ✓ can run a test (4ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.183s
Ran all test suites matching /test\/bundle.test.js/i.

Nice! This means that we can access our production code in unit tests by using Webpack to bundle it all app for us. It also means that as we write more complex tests, we can extract shared testing code and use import to bring it in, just like in any other programming environment.

Next, let's wrap all this up into a script in package.json:

{
  "scripts": {
    "webpack": "webpack --config webpack.config.js --display-error-details",
    "webpack:test": "webpack --config test/webpack.test.config.js --display-error-details",
    "jest": "jest test/bundle.test.js",
    "test": "yarn webpack:test && yarn jest"
  }
}

Now, we can run the entire thing with yarn test:

> yarn test
yarn run v1.13.0
$ yarn webpack:test && yarn jest
$ webpack --config test/webpack.test.config.js --display-error-details
Hash: 023f480a14bd7dbc1c90
Version: webpack 4.29.6
Time: 170ms
Built at: 2019-03-30 10:24:09
         Asset      Size  Chunks             Chunk Names
bundle.test.js  80.2 KiB       0  [emitted]  main
Entrypoint main = bundle.test.js
[0] ./test/canary.test.js 260 bytes {0} [built]
[1] ./js/markdownPreviewer.js 381 bytes {0} [built]
    + 6 hidden modules
$ jest test/bundle.test.js
Done in 2.85s.
PASS test/bundle.test.js
  canary
    ✓ can run a test (3ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.937s, estimated 1s
Ran all test suites matching /test\/bundle.test.js/i.

There's one thing left we need to learn about before moving on. Our current entry point is a single test file, but it's likely we'll have many different test files as our application grows. Let's create test/markdownPreviewer.test.js so that it has our simple test-for-existence, and we'll leave test/canary.test.js as simply asserting the truth.

import markdownPreviewer from "../js/markdownPreviewer"

describe("markdownPreviewer", function() {
  it("should exist", function() {
    expect(markdownPreviewer).toBeDefined();
  });
});

test/canary.test.js should look like so:

describe("canary", function() {
  it("can run a test", function() {
    expect(true).toBe(true);
  });
});

If we run yarn test again, however, we'll only run the test in canary.test.js, because that's the file defined as our entry point for our Webpack test configuration. Webpack's entry key can take an array of files. In this case, Webpack essentially concatenates them all together. For running tests, this is what we want (for our production bundle, you'll recall we have to attach our code to the DOM—that's not something we need to do in unit tests).

While we could itemize out the files in the Webpack config, we'd have to change it every time we added a file, and that's a pain. Instead, we'll use the glob module included by Webpack, which gives us the function sync that will return all files matching a regular expression (it's called sync because it does so synchronously without a callback, which is the right behavior for configuration files). Note that we want to be careful not to include a previous bundle.test.js file, so we'll need to first use glob to get all files matching *.test.js and then remove bundle.test.js from that list. And, because of the weird way Webpack resolves paths, we'll need to prepend each file with ./ so Webpack can find it.

Here's how test/webpack.test.config.js should look:

const path = require('path');
/* start new code */
const glob = require('glob');

const testFiles = glob.sync("**/*.test.js").
                       filter(function(element) {
  return element != "test/bundle.test.js";
}).map(function(element) {
  return "./" + element;
});
/* end new code */

module.exports = {
/* start new code */
  entry: testFiles,
/* end new code */
  output: {
    path: path.resolve(__dirname, "."),
    filename: "bundle.test.js"
  },
  mode: "none"
};

Now, when we run yarn test, we should see two tests running from our two files:

> yarn test
yarn run v1.13.0
$ yarn webpack:test && yarn jest
$ webpack --config test/webpack.test.config.js --display-error-details
Hash: 9a00d9372f469530ce70
Version: webpack 4.29.6
Time: 174ms
Built at: 2019-03-30 10:24:13
         Asset      Size  Chunks             Chunk Names
bundle.test.js  80.4 KiB       0  [emitted]  main
Entrypoint main = bundle.test.js
[0] multi ./test/canary.test.js ./test/markdownPreviewer.test.js 40 bytes {0} [built]
[1] ./test/canary.test.js 107 bytes {0} [built]
[2] ./test/markdownPreviewer.test.js 189 bytes {0} [built]
[3] ./js/markdownPreviewer.js 381 bytes {0} [built]
    + 6 hidden modules
$ jest test/bundle.test.js
Done in 3.09s.
PASS test/bundle.test.js
  canary
    ✓ can run a test (3ms)
  markdownPreviewer
    ✓ should exist

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.917s, estimated 1s
Ran all test suites matching /test\/bundle.test.js/i.

We should now write a real test for markdownPreviewer, but that's outside the scope of learning about Webpack, so we'll leave that as an exercise for you.

There are two potential problems with this setup that we aren't going to worry about. The first is that we have to run webpack and then jest every time we change any file. While we've wrapped that in a convenient alias in package.json, it could be slow as our project grows. Because of Webpack's design, we can't really do much about this other than hope a module is created to address the issue, or learn essentially of all Webpack's internals. Both of those options suck, so let's revisit this issue if it becomes a real problem.

The second problem we're going to ignore for now is that we have two Webpack configurations with some shared similarities. The two configuration files are tiny, and there isn't much duplication, so we'll live with it for now. As we'll see when we configure Webpack for a production deployment, we'll have a way to share common configuration should we need it.

And speaking of production, it's time to sort that out. The only thing worse than code without tests is code that's not in production meeting a real user need, so let's get to it.