Install Mocha via npm:
npm install --global mocha
Or as a dev dependency:
npm install --save-dev mocha
A quick reference guide to Mocha, a JavaScript test framework, covering setup, assertions, hooks, and advanced features for effective testing.
Install Mocha via npm:
Or as a dev dependency:
|
Create a |
Add a test script to your
|
A basic test case includes
|
|
|
Run tests from the command line:
Or using the npm script:
|
Mocha will look for test files in the |
To run a specific test file:
|
Mocha is often used with an assertion library like Chai. Here are some common assertions:
|
Chai provides
|
Hooks are used to set up preconditions and clean up after tests.
|
Example:
|
Mocha supports testing asynchronous code using callbacks, Promises, and async/await. |
Using callbacks:
|
Using Promises: Return a Promise from the
|
Using async/await:
|
For Promises, use |
Mocha has a default timeout of 2000ms. You can change it using
|
To disable timeouts, use |
You can define pending tests (tests without a function body) using
|
You can skip tests using
|
You can run only specific tests using
|
Mocha supports different reporters to format test results. Specify the reporter using the
Common reporters include |