DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The LLM Selection War Story: Part 2 - The Six LLM Failure Archetypes That Will Wreck Your Production System
  • Effective Engineering Feedback: Software Testing
  • CI/CD Integration: Running Playwright on GitHub Actions: The Definitive Automation Blueprint
  • Agentic Development: My Invisible Dev Team

Trending

  • Ten Years of Beam: From Google's Dataflow Paper to 4 Trillion Events at LinkedIn
  • Stop Writing Dialect-Specific SQL: A Unified Query Builder for Node.js
  • Evaluating SOC Effectiveness Using Detection Coverage and Response Metrics
  • Genkit Middleware: Intercept, Extend, and Harden your Gen AI Pipelines
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Unit Testing With Webpack and Mocha

Unit Testing With Webpack and Mocha

After moving our build infrastructure to Webpack, we defined our requirements for the testing infrastructure and created a setup.

By 
Vitaliy Zakharov user avatar
Vitaliy Zakharov
·
Dec. 27, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
13.0K Views

Join the DZone community and get the full member experience.

Join For Free

After moving our build infrastructure to Webpack, one of the hurdles we had to overcome was finding a good way to run unit tests. Quite a few tutorials and how-tos are available for using mocha with Webpack, but none of them gave us all the things we wanted from our test setup.

Therefore, as described below, we defined our requirements for the testing infrastructure and created a setup that enables us to build a test bundle from any number of spec files in a directory, incrementally rebuild on each spec change, and rerun the test suite via mocha on every change.

Test Requirements

We wanted our tests to do the following.

Run Fast

First and foremost, unit tests need to be fast to create and run. It’s hard to argue against the idea that the best time to write unit tests is during development, growing the suite alongside the code. Writing tests after the code is written becomes a chore, and if the suite also takes too long to run, then it’s only natural that code coverage will suffer. I want to be able to write a test, see it fails immediately, write the code, and just as promptly see it pass. Rinse and repeat.

Run in the Terminal

There are legitimate reasons for running unit tests in a browser. For performance and portability, however, we’d rather run them in the terminal.

Use Automatic File Globbing

This one is not an obvious problem at first, but including a whole directory tree of files in Webpack requires a few tricks (i.e., I want to create a *.spec.js file in a directory, and have my suite run it immediately).

The Solution

To address our requirements, we created a master test suite file that will include all tests in the specified directory.

All-tests.js:

var context = require.context('./tests', true, /\.js$/);
context.keys().forEach(context);
module.exports = context;

This will include all js files in the tests subdirectory into the Webpack build.

Now we can do something like:

webpack --entry all-test.js --output-file testBundle.js

However, we still need to be able to run our unit tests after our build finishes. For that purpose, we are going to use webpack-shell-plugin.

npm install --save-dev webpack-shell-plugin

Then, we need to configure Webpack to use the plugin. Let’s create a Webpack config file to include the plugin, as well as persist our entry and output files. We are also including the webpack-node-externals file so our webpack build doesn’t bundle node system files.

webpack-test.config.js:

var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var WebpackShellPlugin = require('webpack-shell-plugin');

var config = {
 entry: 'all-tests.js',
 output: {
   filename: 'testBundle.js'
},
 target: 'node',
 externals: [nodeExternals()],
 node: {
   fs: 'empty'
 },

 plugins: [
   new WebpackShellPlugin({
     onBuildExit: "mocha testBundle.js"
   })
 ]
};

module.exports = config;

Now we should be able to run:

webpack -w --config webpack-test.config.js

Note the -w param, which instructs Webpack to watch for file changes in our test directory as well as do incremental rebuilds. Now our build will execute mocha runner on every test change.

The Results

With this setup, we can build a test bundle from any number of spec files in a directory, incrementally rebuild on each spec change, and rerun the test suite via mocha on every change. Have a look at this working example.

unit test Mocha (JavaScript framework) Test suite

Published at DZone with permission of Vitaliy Zakharov. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The LLM Selection War Story: Part 2 - The Six LLM Failure Archetypes That Will Wreck Your Production System
  • Effective Engineering Feedback: Software Testing
  • CI/CD Integration: Running Playwright on GitHub Actions: The Definitive Automation Blueprint
  • Agentic Development: My Invisible Dev Team

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook