Mocha knows a large number of command-line parameters, but only a few of them are used on a regular basis. For obvious reasons, it is advisable to create an individual mocha.opts template file that can be used as a basis for each application.
--reporterslists all of Mocha's available output formats with a short description.
--reporteractivates one of these output formats. The name of the required output format must be appended to the parameter as an option.
--interfaceslists all of Mocha's available test styles such as TDD and BDD.
--uiactivates one of the test styles, and the name of this style must be appended as before. If no style is appended, Mocha will use BDD by default.
--bailaborts test execution after the first failed test. If this parameter is not included, Mocha will execute all tests and list any failed ones in their order of appearance.
--greplimits the number of tests to be executed to those whose names match a specific pattern. The pattern must be appended to the parameter as an option.
--timeoutdefine limit values for slow and unresponsive tests in milliseconds. The required value must be appended to each parameter as an option.
A typical template for the mocha.opts file could contain the following code:
Mocha in the web browser
Finally, Mocha can be used to test client-side code and execute tests within a web browser. The required initialisation code is slightly more involved than under Node.js. However, as it tends to look the same for each application, the code can be copied from a template that only needs to be generated once, like the contents of the
To execute Mocha in a web browser, the mocha.js and mocha.css files must first be downloaded and then integrated into an HTML page. The two files can be found in Mocha's GitHub repository: mocha.js, mocha.css. A module that will handle the assert phase is also required. The same procedure applies for this module.
When used in a browser, Mocha will generate its output within a div element that must be given the mocha ID. Therefore, the basic framework of a web page for executing Mocha-based client-side unit tests looks like this:
<link rel="stylesheet" type="text/css" href="mocha.css" />
<!-- Systems under test go here -->
<!-- Unit tests go here -->
The actual tests will be written in the same way as those for Node.js. Combining Mocha with the Require.js file and module loader is particularly interesting; with this combination, the same index.html file can be used for each application, and each code segment that is to be tested will be referenced as a dependency in the individual tests.