To test a Node.js application with Mocha, install Mocha as a project development dependency, put test files in test/, write cases with describe and it, and run them with npx mocha. Choose one completion method for each asynchronous test—callback, Promise, or async/await—and use hooks when tests need setup or cleanup.
This guide uses Mocha’s documented v12 requirements and behavior; its compatibility requirement is Node.js ^20.19.0 || >=22.12.0, as of Mocha v12.0.0. See the official getting-started guide for the current installation instructions.
Check Node.js and install Mocha
Check your installed Node.js version before adding Mocha. The v12.0.0 getting-started documentation requires Node.js ^20.19.0 || >=22.12.0. This is a compatibility requirement, not a claim that any particular Mocha version is the latest.
node --version
Install Mocha locally as a development dependency so the project records the test runner alongside its other development tools:
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
npm i -D mocha
With pnpm or Yarn, the equivalent documented installation commands are:
pnpm add -D mocha
yarn add --dev mocha
Use the package manager already used by your project; these commands install the same test runner and do not change the test-writing workflow.
Write and run your first test
Mocha’s default BDD interface provides describe to group related behavior and it to define a test case. Node.js includes an assertion library, so a separate assertion package is not required for a simple test.
Create test/array.test.js in a CommonJS project:
const assert = require('node:assert');
describe('Array#indexOf()', function () {
it('returns -1 when the value is not present', function () {
assert.strictEqual([1, 2, 3].indexOf(4), -1);
});
});
Run the test from the project directory:
npx mocha
Mocha discovers tests in test/ by default. A passing result is reported by the runner; the official guide illustrates the output as 1 passing. That sample describes the guide’s example, not an independently executed result for your project.
Adapt the pattern to application code
The following function is illustrative: put a function in your application module, import it from a test, and assert its documented behavior. For a CommonJS project, for example:
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
// src/discount.js
function discountedPrice(price, percentage) {
return price * (1 - percentage / 100);
}
module.exports = { discountedPrice };
// test/discount.test.js
const assert = require('node:assert');
const { discountedPrice } = require('../src/discount');
describe('discountedPrice', function () {
it('subtracts the specified percentage from the price', function () {
assert.strictEqual(discountedPrice(100, 20), 80);
});
});
Keep the expected result tied to the behavior you intend to preserve. An assertion that only checks a function ran is less useful than one that checks its observable output.
Add a package test script
To make the command repeatable through the project’s normal package workflow, add a script to package.json:
{
"scripts": {
"test": "mocha"
}
}
Then run npm test (or the corresponding test command for your package manager). This script is a convenience wrapper around Mocha; it does not replace Mocha’s CLI.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsChoose one asynchronous completion pattern
Mocha waits for asynchronous work when a test calls its completion callback, returns a Promise, or is declared with async. Match the pattern to the API under test and use only one completion signal in a test. The same approaches are available to asynchronous hooks.
Callback API: use done
For a callback-style API, accept Mocha’s done callback and call it after the operation completes. Pass an error to done to fail the test:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
it('completes a callback operation', function (done) {
readValue((err, value) => {
if (err) return done(err);
try {
assert.strictEqual(value, 'ready');
done();
} catch (assertionError) {
done(assertionError);
}
});
});
readValue is an illustrative callback API; replace it with the application function you are testing. Catching an assertion error inside the callback and forwarding it to done ensures a failed assertion is reported as a test failure.
Promise API: return the Promise
If the operation returns a Promise, return it from the test. Mocha treats fulfillment as completion and a rejection as failure:
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchit('resolves with the value', function () {
return fetchValue().then(function (value) {
assert.strictEqual(value, 'ready');
});
});
fetchValue is illustrative. The important part is returning the Promise chain so Mocha can observe its result.
Promise API: use async/await
An async test returns a Promise automatically, so you can await the operation and assert its result directly:
it('resolves with the value', async function () {
const value = await fetchValue();
assert.strictEqual(value, 'ready');
});
Do not combine a returned Promise with done() in one test. Mocha treats that as overspecified completion because the test signals completion twice.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Use hooks for setup and cleanup
Hooks run code around tests in a suite. before and after run once for their suite; beforeEach and afterEach run around every test in that suite. Hooks may be synchronous or asynchronous.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →describe('shopping cart', function () {
let cart;
beforeEach(function () {
cart = createCart();
});
afterEach(function () {
cart = null;
});
it('starts empty', function () {
assert.strictEqual(cart.items.length, 0);
});
it('accepts an item', function () {
cart.add({ sku: 'book', quantity: 1 });
assert.strictEqual(cart.items.length, 1);
});
});
createCart is illustrative application setup. Creating fresh state in beforeEach keeps one test’s changes from leaking into the next. Use before and after for work genuinely shared across the suite, such as opening and closing a resource once; use per-test hooks when each test needs an isolated fixture.
For asynchronous setup or cleanup, return a Promise or make the hook async. Avoid leaving external resources open after tests: close them in cleanup even when later tests depend on the same suite.
describe('service', function () {
let service;
before(async function () {
service = await connectToService();
});
after(async function () {
await service.close();
});
});
The service functions above are examples, not a database or service implementation. Keep hooks close to the suite they serve. For root-level hooks, Mocha’s documentation recommends Root Hook Plugins as the preferred mechanism since v8; see the hooks guide for details.
Choose CommonJS or ESM deliberately
The first examples use CommonJS (require). Mocha also supports native ECMAScript module tests. Use an .mjs test file, or use .js files in a package whose package.json sets "type": "module".
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
ESM test example
For an ESM project, save the following as test/array.test.mjs:
import assert from 'node:assert';
import { describe, it } from 'mocha';
describe('Array#indexOf()', function () {
it('returns -1 when the value is not present', function () {
assert.strictEqual([1, 2, 3].indexOf(4), -1);
});
});
Alternatively, save it as test/array.test.js under a package configured with "type": "module". The documented limitation is that Mocha watch mode does not support ESM test files. If you rely on plugins, custom reporters, or less common modes, check the current Mocha documentation for their module-format compatibility rather than assuming every setup behaves identically.
Keep configuration simple, then make it repeatable
Start with npx mocha. Add persistent configuration only when the project needs options shared across runs. Mocha supports configuration in several formats, including .mocharc.js, .mocharc.cjs, .mocharc.mjs, YAML, JSON, and JSONC, as well as a mocha property in package.json. The configuration documentation describes the available forms.
When settings overlap, Mocha applies this precedence from highest to lowest:
- Command-line flags
MOCHA_OPTIONSenvironment variable- Mocha configuration file
mochaproperty inpackage.json
That order lets a one-off command override shared defaults, while environment settings can adjust an invocation without editing the project configuration.
CLI options worth adding selectively
Mocha’s CLI reference documents a default spec reporter and a two-second timeout; retries are opt-in. It also documents parallel test-file execution with --parallel and rerunning tests after changes with --watch. Defaults and options are version-sensitive, so consult the CLI reference for the version installed in your project.
- Use
--timeoutwhen legitimate operations need more time, rather than treating a timeout as proof that the test passed. - Consider
--parallelonly when test files can run independently and the project is ready for worker-based execution. - Use
--watchfor a quick edit-and-rerun loop, keeping in mind the ESM watch-mode limitation. - Retries are not a substitute for fixing nondeterministic tests; enable them only when the retry behavior is appropriate to your suite.
Troubleshoot common failures
- Mocha will not start under your Node.js version: Compare
node --versionwith the v12.0.0 requirement^20.19.0 || >=22.12.0. Upgrade Node.js to a compatible release or use a Mocha version supported by your project’s runtime. - No tests are found: Check that files are under the default
test/directory, use a recognized test-file extension, and runnpx mochafrom the project root. If your tests live elsewhere, consult the CLI reference for how to specify them. - A callback test hangs: Ensure every successful callback path calls
done()and every error path passes the error todone(err). Also check that the underlying callback is actually invoked. - Mocha reports overspecified completion: Remove either the returned Promise or the
donecallback. A test must use one completion mechanism, not both. - An asynchronous assertion appears to pass unexpectedly: Return the Promise or make the test
asyncand await it. Otherwise Mocha may finish before the asynchronous assertion runs. - Setup works for one test but leaks state into another: Move per-test fixture creation and cleanup into
beforeEachandafterEach, rather than sharing mutable state with suite-level hooks. - ESM tests do not rerun in watch mode: Mocha documents that ESM test files are not supported by watch mode. Run the tests without watch mode or use a compatible test setup.
- A setting seems ignored: Check whether a higher-precedence CLI flag or
MOCHA_OPTIONSvalue overrides the config file orpackage.jsonsetting.
Or skip the browser setup
Mocha is for running Node.js tests. If you also need website screenshots for a test workflow, ScreenshotNeo returns an image or PDF from one GET request. For example, this cURL command saves a WebP screenshot:
Quick Recap
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for parameters and response details. Cookie banners, popups, and chat widgets are removed before capture; bot checks, blank pages, failed loads, and cache hits are not billed. An MCP server provides screenshot tools for AI agents, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for free.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

