Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser. It runs independently from the assertion library, so you can choose whichever works for you. It allows you to choose other interfaces for defining test suites besides TDD, like BDD, Exports, QUnit and Require. You can also integrate generators into your test suite or custom the colors of the test reporters.
Some downsides are that tests cannot be ran in random order and that Mocha requires developers to select and set up assertion libraries and mocking utilities, which can be intimidating for beginners.
You can install Mocha using the Node Package Manager (NPM).
With global installation
npm i --global mocha
This makes the mocha CLI binary available for use in your command-line terminal so you can run tests using: mocha
You can also install it as a development dependency for your project
npm i --save-dev mocha
If you this you can access the mocha
binary from the node_modules
directory of your project as follows: ./node_modules/mocha/bin/mochamocha
Mocha automatically looks for tests inside the test directory of your project. So you should go ahead and create a directory with that name in your project root.
Writing tests often requires using an assertion library. If you are using Mocha in a Node.js environment, you can use the built-in assert module as your assertion library. However, there are other options such as Chai, Expect.js, Should.js.
Mocha also provides a variety of style-interfaces for defining test suites: BDD, TDD, Exports, QUnit and Require. If you want to know more about them you can check out Mocha’s documentation.
Here is a simple example in which the Chai assertion library and BDD interface are used:
https://github.com/CarminaP/MochaTesting
While on the project root you can run the test script using mocha
. The output should looke like this:
Resources:
https://www.slant.co/options/12696/~mocha-review
https://blog.logrocket.com/a-quick-and-complete-guide-to-mocha-testing-d0e0ea09f09d