Mocha & Chai
Installation
npm i -D mocha chai
More at:
Usage
./node_modules/mocha/bin/mocha <test-file?> [option]
# Use with npm scripts
npm test -- [option]
// package.json e.g.:
{
"scripts": {
"test" : "mocha <test-file?> [option]"
}
}
Options:
-b, --bail <boolean>
(abort after first fail)--exit <boolean>
(force to quit after tests complete)-j, --jobs <number>
(jobs to run in parallel)-p, --parallel <boolean>
--config <config-file>
(.mocharc.js
by default)--extension [extension]
(['js', 'cjs', 'mjs']
by default)-w
,--watch <boolean>
-r
,--require <module>
(preload modules before testing)
More at COMMAND-LINE USAGE (mochajs.org).
Configuration
By default, a mocha configuration file is named .mocharc
, its extensions could be js|cjs|json|jsonc|yaml|yml
.
// .mocharc.js e.g.:
'use-strict';
module.exports = {
bail: true,
extension: ['js'],
// ...
}
More at:
Using ESMs
1- Setup package file:
// package.json e.g.:
{
"type": "module"
}
2- Setup test files:
// main.test.js e.g.:
import { assert } from 'chai';
import foo from './bar.js'; // *
*Use file extensions for relative/absolute module paths, see Mandatory file extensions (nodejs.org).
More at Assert (chaijs.com).
Using TypeScript ESMs
1- Install TypeScript, TS-Node for running .ts
files like tsc + node
, Mocha types, and Chai types:
npm i -D typescript ts-node @types/mocha @types/chai
2- Setup package file. To avoid conflicts with other tsconfig
files, specify a different one through the environment variable TS_NODE_PROJECT
(notice there’s no space after the path value):
// package.json e.g.:
{
"type": "module",
"scripts": {
"test" : "set TS_NODE_PROJECT=tsconfig.test.json&& mocha"
// Or "test" : "env TS_NODE_PROJECT=tsconfig.test.json mocha" on Linux/Mac?
}
}
3- Setup Mocha configuration file:
// .mocharc.json e.g.:
{
"experimental-json-modules": true,
"extensions": [
"ts"
],
"loader": "ts-node/esm",
"recursive": true,
"spec": [
"test/**/*.spec.ts"
]
}
4- Setup TypeScript configuration file (compilerOptions
inside ts-node
can override compilerOptions
from outside it, which are the ones used by tsc
):
// tsconfig.test.json e.g.:
{
"ts-node": {
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
"target": "ESNext"
},
"files": true,
"esm": true
}
}
More at: