Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →To test a Node.js application with Mocha, install Mocha locally, put a test in test/, write an assertion, and run npx mocha. This tutorial walks through that setup, then shows how to test asynchronous code, isolate tests with hooks, choose CommonJS or ESM, and keep settings repeatable.
Check Node.js and install Mocha
Mocha’s getting-started guide documents its v12.0.0 requirement as Node.js ^20.19.0 || >=22.12.0. Check the runtime in your project before installing:
node --version
If your version does not meet that requirement, use a compatible Node.js release or consult the documentation for a Mocha version that supports your runtime. Install Mocha as a development dependency so the project records the test runner:
npm install --save-dev mocha
The equivalent commands for other package managers are pnpm add --save-dev mocha and yarn add --dev mocha. These are installation alternatives; the test workflow below remains the same. See Mocha’s Getting Started guide for current requirements and package-manager guidance.
#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.
Write and run your first test
Mocha discovers tests in the conventional test/ directory. This CommonJS-compatible example uses Node’s built-in assertion module, so it needs no assertion-library dependency. Save it as test/example.test.js:
const assert = require('node:assert');
describe('Array#indexOf()', function () {
it('returns -1 when the value is absent', function () {
assert.strictEqual([1, 2, 3].indexOf(4), -1);
});
});
describe groups related behavior and it states the expected outcome. Run the suite from the project root:
npx mocha
The getting-started guide illustrates a successful run with 1 passing; that is an example of expected output, not a result from an independently run test here. If the command cannot find a test, verify the working directory and that the file is inside test/.
To make the command available through the project’s usual package script, add this entry to package.json:
Free tools Windows power users keep installed
One-click scans. No signup required.
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.
{
"scripts": {
"test": "mocha"
}
}
Then run npm test. The script is simply a repeatable wrapper around Mocha’s command.
Test your application’s behavior
A useful test exercises an application behavior rather than merely confirming that a library behaves as documented. For example, if a project exports a function named normalizeName, a test could assert the contract the application expects:
const assert = require('node:assert');
const { normalizeName } = require('../src/normalize-name');
describe('normalizeName', function () {
it('trims surrounding whitespace', function () {
assert.strictEqual(normalizeName(' Ada '), 'Ada');
});
});
This assumes your project actually exports that function from src/normalize-name.js; change the import and expected behavior to match your code. Keep each test focused on a behavior and an observable result. Use strict assertions such as assert.strictEqual where exact equality is the contract, and choose other assertions from Node’s node:assert API when the behavior calls for them.
Choose one completion pattern for asynchronous tests
Mocha needs to know when an asynchronous test has finished. Choose the completion mechanism that matches the API under test: callback completion for callback APIs, a returned Promise for Promise APIs, or async/await for an asynchronous flow. Do not return a Promise and also call done() in the same test; Mocha treats the two signals as overspecified completion. The same patterns apply to asynchronous hooks. See Mocha’s asynchronous-code guide.
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.
Callback API: signal completion with done
it('loads a record through a callback API', function (done) {
loadRecord('record-1', function (err, record) {
if (err) return done(err);
try {
assert.strictEqual(record.id, 'record-1');
done();
} catch (assertionError) {
done(assertionError);
}
});
});
This is an illustrative pattern: replace loadRecord with your callback-based function. Pass callback errors to done(err). Assertions inside callbacks should also reach Mocha as errors, as shown, rather than being lost in asynchronous code.
Promise API: return the Promise
it('resolves with a record', function () {
return loadRecord('record-1').then(function (record) {
assert.strictEqual(record.id, 'record-1');
});
});
Returning the Promise lets Mocha wait for settlement and report a rejection as a failure. The function name is illustrative; use your Promise-returning API.
Async function: await the operation
it('resolves with a record', async function () {
const record = await loadRecord('record-1');
assert.strictEqual(record.id, 'record-1');
});
An async test returns a Promise automatically. Use either this pattern or the explicit Promise-returning form, not done as well.
Use hooks to set up and clean up fixtures
The default BDD interface provides four hooks. Use suite-level hooks for work that genuinely happens once around a group of tests, and per-test hooks when each case needs an independent setup and cleanup:
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
| Hook | When it runs | Typical role |
|---|---|---|
before |
Once before tests in its suite | Create a shared fixture or establish suite prerequisites |
after |
Once after tests in its suite | Release suite-level resources |
beforeEach |
Before each test in its suite | Reset state so a case starts independently |
afterEach |
After each test in its suite | Restore state or clean up per-test resources |
Hooks can be synchronous or asynchronous. This illustrative example uses a hypothetical fixture API:
describe('user service', function () {
let fixture;
beforeEach(async function () {
fixture = await createUserFixture();
});
afterEach(async function () {
await fixture.dispose();
});
it('finds a user by ID', async function () {
const user = await fixture.service.findById(fixture.user.id);
assert.strictEqual(user.id, fixture.user.id);
});
});
createUserFixture and its methods are examples, not an included database implementation. Prefer local hooks within the suite that needs them; this makes dependencies and cleanup easier to see. For hooks that apply at the root level, Mocha recommends Root Hook Plugins rather than relying on root hooks since Mocha v8. Details are in the hooks documentation.
Choose CommonJS or ESM deliberately
The first examples use CommonJS (require). Mocha also supports native ECMAScript modules. For ESM, either save the test with a .mjs extension or use a .js file in a package whose package.json sets "type": "module". An ESM test can import Node’s assertion module like this:
import assert from 'node:assert';
describe('Array#indexOf()', function () {
it('returns -1 when the value is absent', function () {
assert.strictEqual([1, 2, 3].indexOf(4), -1);
});
});
Mocha’s documented limitation is that watch mode does not support ESM test files. Do not assume every plugin, reporter, or test mode behaves identically across module systems; check the relevant current documentation when adding one. See Mocha’s ESM guide.
Recommended Free Tools
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.
Make test settings repeatable
Start with npx mocha and add persistent configuration only when the project needs it. Mocha supports configuration in .mocharc.js, .mocharc.cjs, .mocharc.mjs, YAML, JSON or JSONC files, and in a mocha property in package.json. For example, a package-level property can select a test directory pattern:
{
"mocha": {
"spec": "test/**/*.js"
}
}
When settings conflict, the precedence is command-line flags, then MOCHA_OPTIONS, then a configuration file, then the mocha property in package.json. A command-line flag is therefore suitable for a one-off override; a config file or package property is better for shared project defaults. See the configuration documentation.
Add CLI options to solve a specific need
The CLI reference describes a default spec reporter and a 2-second timeout; retries are opt-in. It also documents --parallel for running files in a worker pool and --watch for rerunning tests after changes. These are options, not requirements for every project. Parallel execution may be a poor fit for tests that share mutable external state, and watch mode has the ESM limitation noted above. Review the current Mocha CLI reference before relying on defaults or flags, since CLI behavior can change.
Troubleshoot common failures
- Mocha reports a Node.js version or syntax compatibility problem: compare
node --versionwith the documented v12 requirement above, and use a compatible runtime. - No tests are found: run the command from the project root and check that files are under
test/, or set the intended pattern in a supported config. - An asynchronous test finishes too early or hangs: make sure the test uses exactly one completion mechanism and that a callback calls
doneon both success and error paths. A Promise-based API should return or be awaited. - Mocha reports overspecified completion: remove either the returned Promise or the
donecallback; do not combine them in one test. - Tests pass alone but interfere with each other: move state reset into
beforeEachor cleanup intoafterEach, and avoid depending on test execution order. - ESM tests do not rerun in watch mode: Mocha documents that ESM test files are unsupported in watch mode; run them without watch or use an appropriate CommonJS arrangement if watch is necessary.
- A setting appears ignored: check for a higher-precedence command-line flag or
MOCHA_OPTIONSvalue before changing the config file.
Or skip the browser setup
This Node.js tutorial is about test runners, not website screenshot capture, but developers who need screenshots for a separate workflow can use ScreenshotNeo. Its API takes one GET request for a URL and returns an image or PDF. For example, with cURL:
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 setup and options. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed; an MCP server lets AI agents take screenshots; and 1,000 screenshots a month are free with no card, with paid plans starting at $5 for 3,000. Sign up for the free plan.
Frequently Asked Questions
Can Mocha run tests without an assertion library?
Yes. Node.js provides the built-in node:assert module used in this tutorial.
Quick Recap
Does Mocha run tests in parallel by default?
No. Parallel execution is an opt-in CLI mode.
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.




