Getting Started
1. Installation
First, install the mocha
package as a devDependency using your favorite package manager:
npm i -D mocha
yarn add -D mocha
pnpm add -D mocha
2. Test File
Create the following example.test.js
file under a test/
directory:
import { assert } from "node:assert";
describe("Array", function () { describe("#indexOf()", function () { it("should return -1 when the value is not present", function () { assert.equal([1, 2, 3].indexOf(4), -1); }); });});
3. Running Mocha
Now, run npx mocha
to execute the Mocha package on the newly created test file:
npx mocha
You should see passing output like:
Array #indexOf() ✓ should return -1 when the value is not present
1 passing (9ms)
Optional: test
script
Most projects include a package.json
"test"
script:
{ "scripts": { "test": "mocha" }}
You can then run that script with your favorite package manager:
npm run test
yarn run test
pnpm run test
Next Steps
See:
- CLI for the commands you can pass to
mocha
- Configuring for creating a persistent test configuration file
- Editor Plugins for improving the Mocha experience in your editor
You can see real live live example code in our example repositories: