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:
- test our modules in isolation
- execute a single test while we drive functionality in a module.
- run tests without having to pop up a browser.
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.21.1
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
info This module is OPTIONAL, you can safely ignore this error
success Saved lockfile.
success Saved 180 new dependencies.
info Direct dependencies
└─ jest@24.9.0
info All dependencies
├─ @babel/helper-function-name@7.8.3
├─ @babel/helper-get-function-arity@7.8.3
├─ @babel/helper-plugin-utils@7.8.3
├─ @babel/helper-split-export-declaration@7.8.3
├─ @babel/helpers@7.8.3
├─ @babel/highlight@7.8.3
├─ @babel/plugin-syntax-object-rest-spread@7.8.3
├─ @cnakazawa/watch@1.0.3
├─ @jest/core@24.9.0
├─ @jest/reporters@24.9.0
├─ @jest/source-map@24.9.0
├─ @jest/test-sequencer@24.9.0
├─ @types/babel__core@7.1.3
├─ @types/babel__generator@7.6.1
├─ @types/babel__template@7.0.2
├─ @types/babel__traverse@7.0.8
├─ @types/istanbul-lib-report@3.0.0
├─ @types/istanbul-reports@1.1.1
├─ @types/stack-utils@1.0.1
├─ @types/yargs-parser@15.0.0
├─ acorn-globals@4.3.4
├─ acorn-walk@6.2.0
├─ array-equal@1.0.0
├─ asn1@0.2.4
├─ astral-regex@1.0.0
├─ async-limiter@1.0.1
├─ asynckit@0.4.0
├─ aws-sign2@0.7.0
├─ aws4@1.9.1
├─ babel-jest@24.9.0
├─ babel-plugin-jest-hoist@24.9.0
├─ babel-preset-jest@24.9.0
├─ bcrypt-pbkdf@1.0.2
├─ browser-process-hrtime@0.1.3
├─ browser-resolve@1.11.3
├─ bser@2.1.1
├─ capture-exit@2.0.0
├─ caseless@0.12.0
├─ ci-info@2.0.0
├─ co@4.6.0
├─ combined-stream@1.0.8
├─ convert-source-map@1.7.0
├─ cssom@0.3.8
├─ cssstyle@1.4.0
├─ dashdash@1.14.1
├─ data-urls@1.1.0
├─ deep-is@0.1.3
├─ delayed-stream@1.0.0
├─ detect-newline@2.1.0
├─ diff-sequences@24.9.0
├─ domexception@1.0.1
├─ ecc-jsbn@0.1.2
├─ error-ex@1.3.2
├─ es-abstract@1.17.4
├─ es-to-primitive@1.2.1
├─ escodegen@1.13.0
├─ esprima@4.0.1
├─ extend@3.0.2
├─ extsprintf@1.3.0
├─ fast-levenshtein@2.0.6
├─ forever-agent@0.6.1
├─ form-data@2.3.3
├─ gensync@1.0.0-beta.1
├─ getpass@0.1.7
├─ globals@11.12.0
├─ growly@1.3.0
├─ har-schema@2.0.0
├─ har-validator@5.1.3
├─ hosted-git-info@2.8.5
├─ html-encoding-sniffer@1.0.2
├─ html-escaper@2.0.0
├─ http-signature@1.2.0
├─ iconv-lite@0.4.24
├─ invariant@2.2.4
├─ is-arrayish@0.2.1
├─ is-callable@1.1.5
├─ is-date-object@1.0.2
├─ is-generator-fn@2.1.0
├─ is-regex@1.0.5
├─ is-symbol@1.0.3
├─ is-typedarray@1.0.0
├─ isstream@0.1.2
├─ istanbul-lib-instrument@3.3.0
├─ istanbul-lib-report@2.0.8
├─ istanbul-lib-source-maps@3.0.6
├─ istanbul-reports@2.2.7
├─ jest-changed-files@24.9.0
├─ jest-cli@24.9.0
├─ jest-docblock@24.9.0
├─ jest-each@24.9.0
├─ jest-environment-jsdom@24.9.0
├─ jest-environment-node@24.9.0
├─ jest-leak-detector@24.9.0
├─ jest-pnp-resolver@1.2.1
├─ jest-resolve-dependencies@24.9.0
├─ jest-serializer@24.9.0
├─ jest-watcher@24.9.0
├─ jest@24.9.0
├─ js-tokens@4.0.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.3
├─ left-pad@1.3.0
├─ leven@3.1.0
├─ levn@0.3.0
├─ load-json-file@4.0.0
├─ lodash@4.17.15
├─ loose-envify@1.4.0
├─ makeerror@1.0.11
├─ merge-stream@2.0.0
├─ mime-db@1.43.0
├─ mime-types@2.1.26
├─ ms@2.1.2
├─ natural-compare@1.4.0
├─ node-int64@0.4.0
├─ node-modules-regexp@1.0.0
├─ node-notifier@5.4.3
├─ normalize-package-data@2.5.0
├─ nwsapi@2.2.0
├─ oauth-sign@0.9.0
├─ object-inspect@1.7.0
├─ object-keys@1.1.1
├─ object.assign@4.1.0
├─ object.getownpropertydescriptors@2.1.0
├─ optionator@0.8.3
├─ 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
├─ pn@1.1.0
├─ prompts@2.3.0
├─ psl@1.7.0
├─ qs@6.5.2
├─ react-is@16.12.0
├─ read-pkg-up@4.0.0
├─ read-pkg@3.0.0
├─ request-promise-core@1.1.3
├─ request-promise-native@1.0.8
├─ request@2.88.0
├─ resolve@1.14.2
├─ rsvp@4.8.5
├─ safer-buffer@2.1.2
├─ sane@4.1.0
├─ sax@1.2.4
├─ shellwords@0.1.1
├─ sisteransi@1.0.4
├─ spdx-correct@3.1.0
├─ spdx-exceptions@2.2.0
├─ sshpk@1.16.1
├─ stack-utils@1.0.2
├─ stealthy-require@1.1.1
├─ string.prototype.trimleft@2.1.1
├─ string.prototype.trimright@2.1.1
├─ symbol-tree@3.2.4
├─ test-exclude@5.2.3
├─ tmpl@1.0.4
├─ to-fast-properties@2.0.0
├─ tough-cookie@2.5.0
├─ tunnel-agent@0.6.0
├─ tweetnacl@0.14.5
├─ util.promisify@1.0.1
├─ uuid@3.4.0
├─ validate-npm-package-license@3.0.4
├─ verror@1.10.0
├─ w3c-hr-time@1.0.1
├─ walker@1.0.7
├─ whatwg-encoding@1.0.5
├─ whatwg-mimetype@2.3.0
├─ whatwg-url@6.5.0
├─ word-wrap@1.2.3
├─ write-file-atomic@2.4.1
├─ ws@5.2.2
└─ xml-name-validator@3.0.0
Done in 8.44s.
warning jest > jest-cli > jest-config > jest-environment-jsdom > jsdom > left-pad@1.3.0: use String.prototype.padStart()
warning Error running install script for optional dependency: "/Users/davec/Projects/Personal/wtf-is-a-webpack/work/work/node_modules/fsevents: Command failed.
Exit code: 1
Command: node-gyp rebuild
Arguments:
Directory: /Users/davec/Projects/Personal/wtf-is-a-webpack/work/work/node_modules/fsevents
Output:
gyp info it worked if it ends with ok
gyp info using node-gyp@3.8.0
gyp info using node@12.3.0 | darwin | x64
gyp info spawn /usr/bin/python
gyp info spawn args [
gyp info spawn args '/Users/davec/.asdf/installs/nodejs/12.3.0/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args 'binding.gyp',
gyp info spawn args '-f',
gyp info spawn args 'make',
gyp info spawn args '-I',
gyp info spawn args '/Users/davec/Projects/Personal/wtf-is-a-webpack/work/work/node_modules/fsevents/build/config.gypi',
gyp info spawn args '-I',
gyp info spawn args '/Users/davec/.asdf/installs/nodejs/12.3.0/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
gyp info spawn args '-I',
gyp info spawn args '/Users/davec/.node-gyp/12.3.0/include/node/common.gypi',
gyp info spawn args '-Dlibrary=shared_library',
gyp info spawn args '-Dvisibility=default',
gyp info spawn args '-Dnode_root_dir=/Users/davec/.node-gyp/12.3.0',
gyp info spawn args '-Dnode_gyp_dir=/Users/davec/.asdf/installs/nodejs/12.3.0/lib/node_modules/npm/node_modules/node-gyp',
gyp info spawn args '-Dnode_lib_file=/Users/davec/.node-gyp/12.3.0/<(target_arch)/node.lib',
gyp info spawn args '-Dmodule_root_dir=/Users/davec/Projects/Personal/wtf-is-a-webpack/work/work/node_modules/fsevents',
gyp info spawn args '-Dnode_engine=v8',
gyp info spawn args '--depth=.',
gyp info spawn args '--no-parallel',
gyp info spawn args '--generator-output',
gyp info spawn args 'build',
gyp info spawn args '-Goutput_dir=.'
gyp info spawn args ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
SOLINK_MODULE(target) Release/.node
CXX(target) Release/obj.target/fse/fsevents.o
In file included from ../fsevents.cc:6:
In file included from ../../nan/nan.h:54:
/Users/davec/.node-gyp/12.3.0/include/node/node.h:107:12: fatal error: 'util-inl.h' file not found
# include <util-inl.h>
^~~~~~~~~~~~
1 error generated.
make: *** [Release/obj.target/fse/fsevents.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/Users/davec/.asdf/installs/nodejs/12.3.0/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack at ChildProcess.emit (events.js:200:13)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)
gyp ERR! System Darwin 18.7.0
gyp ERR! command \"/Users/davec/.asdf/installs/nodejs/12.3.0/bin/node\" \"/Users/davec/.asdf/installs/nodejs/12.3.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js\" \"rebuild\"
gyp ERR! cwd /Users/davec/Projects/Personal/wtf-is-a-webpack/work/work/node_modules/fsevents
gyp ERR! node -v v12.3.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok"
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.
[boolean]
--automock Automock all files by default. [boolean]
--bail, -b Exit the test suite immediately after `n` number
of failing tests. [boolean]
--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. Implies
`runInBand`. [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) [string]
--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]
--testSequencer Allows to specify a custom test sequencer. The
default is `@jest/test-sequencer`. A path to a
custom test sequencer can be provided:
`<rootDir>/path/to/testSequencer.js` [string]
--testTimeout This option sets the default timeouts of test
cases. [number]
--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 (2ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.036s
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:537:17)
at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.057s
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.41.5
Time: 164ms
Built at: 01/21/2020 5:45:58 PM
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 (2ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.93s
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.21.1
$ yarn webpack:test && yarn jest
$ webpack --config test/webpack.test.config.js --display-error-details
Hash: 023f480a14bd7dbc1c90
Version: webpack 4.41.5
Time: 186ms
Built at: 01/21/2020 5:46:03 PM
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.93s.
PASS test/bundle.test.js
canary
✓ can run a test (2ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.077s, estimated 2s
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.21.1
$ yarn webpack:test && yarn jest
$ webpack --config test/webpack.test.config.js --display-error-details
Hash: 9cad57c64bf77d797079
Version: webpack 4.41.5
Time: 317ms
Built at: 01/21/2020 5:46:07 PM
Asset Size Chunks Chunk Names
bundle.test.js 144 KiB 0 [emitted] main
Entrypoint main = bundle.test.js
[0] multi ./node_modules/gensync/test/index.test.js ./test/canary.test.js ./test/markdownPreviewer.test.js 52 bytes {0} [built]
[17] (webpack)/buildin/global.js 472 bytes {0} [built]
[52] ./test/canary.test.js 107 bytes {0} [built]
[53] ./test/markdownPreviewer.test.js 189 bytes {0} [built]
[54] ./js/markdownPreviewer.js 381 bytes {0} [built]
+ 52 hidden modules
$ jest test/bundle.test.js
console.log node_modules/jest-jasmine2/build/jasmine/Env.js:502
● Test suite failed to run
Returning a Promise from "describe" is not supported. Tests must be defined synchronously.
Returning a value from "describe" will fail the test in a future version of Jest.
299 | });
300 |
> 301 | describe("'sync' handler", async () => {
| ^
302 | test("success", async () => {
303 | const fn = gensync({
304 | sync: (...args) => JSON.stringify(args),
at addSpecsToSuite (node_modules/jest-jasmine2/build/jasmine/Env.js:504:17)
at Suite.<anonymous> (test/bundle.test.js:301:3)
at Object.call (test/bundle.test.js:162:1)
at Object.call (test/bundle.test.js:577:30)
at __webpack_require__ (test/bundle.test.js:20:30)
at Object.call (test/bundle.test.js:91:1)
at __webpack_require__ (test/bundle.test.js:20:30)
at test/bundle.test.js:84:18
at Object.<anonymous> (test/bundle.test.js:1:10)
console.log node_modules/jest-jasmine2/build/jasmine/Env.js:502
● Test suite failed to run
Returning a Promise from "describe" is not supported. Tests must be defined synchronously.
Returning a value from "describe" will fail the test in a future version of Jest.
319 | });
320 |
> 321 | describe("'async' handler", async () => {
| ^
322 | test("success", async () => {
323 | const fn = gensync({
324 | sync: throwTestError,
at addSpecsToSuite (node_modules/jest-jasmine2/build/jasmine/Env.js:504:17)
at Suite.<anonymous> (test/bundle.test.js:321:3)
at Object.call (test/bundle.test.js:162:1)
at Object.call (test/bundle.test.js:577:30)
at __webpack_require__ (test/bundle.test.js:20:30)
at Object.call (test/bundle.test.js:91:1)
at __webpack_require__ (test/bundle.test.js:20:30)
at test/bundle.test.js:84:18
at Object.<anonymous> (test/bundle.test.js:1:10)
console.log node_modules/jest-jasmine2/build/jasmine/Env.js:502
● Test suite failed to run
Returning a Promise from "describe" is not supported. Tests must be defined synchronously.
Returning a value from "describe" will fail the test in a future version of Jest.
339 | });
340 |
> 341 | describe("'errback' sync handler", async () => {
| ^
342 | test("success", async () => {
343 | const fn = gensync({
344 | sync: throwTestError,
at addSpecsToSuite (node_modules/jest-jasmine2/build/jasmine/Env.js:504:17)
at Suite.<anonymous> (test/bundle.test.js:341:3)
at Object.call (test/bundle.test.js:162:1)
at Object.call (test/bundle.test.js:577:30)
at __webpack_require__ (test/bundle.test.js:20:30)
at Object.call (test/bundle.test.js:91:1)
at __webpack_require__ (test/bundle.test.js:20:30)
at test/bundle.test.js:84:18
at Object.<anonymous> (test/bundle.test.js:1:10)
console.log node_modules/jest-jasmine2/build/jasmine/Env.js:502
● Test suite failed to run
Returning a Promise from "describe" is not supported. Tests must be defined synchronously.
Returning a value from "describe" will fail the test in a future version of Jest.
359 | });
360 |
> 361 | describe("'errback' async handler", async () => {
| ^
362 | test("success", async () => {
363 | const fn = gensync({
364 | sync: throwTestError,
at addSpecsToSuite (node_modules/jest-jasmine2/build/jasmine/Env.js:504:17)
at Suite.<anonymous> (test/bundle.test.js:361:3)
at Object.call (test/bundle.test.js:162:1)
at Object.call (test/bundle.test.js:577:30)
at __webpack_require__ (test/bundle.test.js:20:30)
at Object.call (test/bundle.test.js:91:1)
at __webpack_require__ (test/bundle.test.js:20:30)
at test/bundle.test.js:84:18
at Object.<anonymous> (test/bundle.test.js:1:10)
Done in 4.13s.
PASS test/bundle.test.js
gensync({})
option validation
✓ disallow async and errback handler together (3ms)
✓ disallow missing sync handler (1ms)
✓ errback callback required
generator function metadata
✓ automatic naming (1ms)
✓ explicit naming (1ms)
✓ default arity
✓ explicit arity
'sync' handler
✓ success (8ms)
✓ failure (2ms)
'async' handler
✓ success (2ms)
✓ failure (1ms)
'errback' sync handler
✓ success
✓ failure (1ms)
'errback' async handler
✓ success (9ms)
✓ failure (4ms)
gensync(function* () {})
✓ sync throw before body (1ms)
✓ sync throw inside body (1ms)
✓ async throw inside body
✓ error inside body (3ms)
✓ successful return value
✓ successful final value (1ms)
✓ yield unexpected object
✓ yield suspend yield
✓ yield suspend return (1ms)
gensync.all()
✓ success (2ms)
✓ error first (1ms)
✓ error last
gensync.race()
✓ success (1ms)
✓ error (1ms)
canary
✓ can run a test
markdownPreviewer
✓ should exist
Test Suites: 1 passed, 1 total
Tests: 31 passed, 31 total
Snapshots: 0 total
Time: 1.934s
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.