Catalog / Mocha Testing Cheatsheet
Mocha Testing Cheatsheet
A quick reference guide to Mocha, a JavaScript test framework, covering setup, assertions, hooks, and advanced features for effective testing.
Mocha Setup and Basics
Installation & Setup
Install Mocha via npm:
Or as a dev dependency:
|
Create a |
Add a test script to your
|
Basic Test Structure
A basic test case includes
|
|
|
Running Tests
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:
|
Assertions and Hooks
Common Assertions
Mocha is often used with an assertion library like Chai. Here are some common assertions:
|
Chai Assertions (BDD Style)
Chai provides
|
Hooks
Hooks are used to set up preconditions and clean up after tests.
|
Example:
|
Asynchronous Testing
Testing Asynchronous Code
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 |
Timeouts
Mocha has a default timeout of 2000ms. You can change it using
|
To disable timeouts, use |
Advanced Mocha Features
Pending Tests
You can define pending tests (tests without a function body) using
|
Skipping Tests
You can skip tests using
|
Only Running Specific Tests
You can run only specific tests using
|
Reporters
Mocha supports different reporters to format test results. Specify the reporter using the
Common reporters include |