Mocha.js Basics

Persis Randolph
4 min readMay 10, 2021

--

Photo by Frame Harirak on Unsplash

Testing is a crucial step of the development process. Having comprehensive tests allows for developers to safely make changes without the fear of having caused bugs in another part of the program, or unintentional side effects. A thorough set of tests would expose these errors quickly and make sure that the program was still in working order when the bug-fix or new feature was released. The goal is to expose problems as quickly as possible, allow for easy debugging, and no unintentional steps backward in functionality.

Mocha is a great example and one of the most popular frameworks you can use for this testing. It’s an open-source JavaScript testing library that runs on Node.js and in the browser. Since Mocha was designed specifically for testing Node applications, it has more back-end tools and documentation compared to other testing frameworks. However, it does generally require more dependencies than other testing libraries, and is typically used in conjunction with the assertion library, Chai.

It uses Behavior Driven Development (BDD) to describe expected behaviors in a way that is clear to all contributors to the software, instead of just the testers and the developers. BDD expands from Test Driven Development (TDD) in this way. Using language close to common English allows accessibility of intention to be understood by others with stakes in the same project (project managers, salespeople, product owners, etc.) and reads more simply than some other testing frameworks.

expect(2 + 2).to.equal(4);
expect(exampleArray).to.have.lengthOf(7);

Mocha executes tests in the specified order and logs results to the terminal or the browser, depending on how the tests are set up. It uses unit testing, which is breaking up the behavior of code into small bits, and testing each behavior at the smallest meaningful chunk of independent code. For this to occur properly, it is important to have independent test cases. Each test run must not affect the software state. There are built-in tools for cleaning the software state — using stub or mock.

Prerequisites and Set-Up

The only prerequisites for using Mocha are the installation of node and npm.

To use Mocha for a project, using npm, you can install globally, usingnpm install -global mocha, or you can install it as a dependency for a single project while in that project’s root folder, usingnpm install mocha.

Mocha expects a directory created in the project called “test” which specifically contains the test files. If this has been done, you can run tests in the terminal using the prompt mocha (or mocha --recursive if you need to include subdirectories). You can also include a script in package.json if you’d like to run tests using the shorthand npm test.

"scripts": {
"test": "mocha"
}

Running the tests will display formatted text in the terminal/console to display details on whether your tests passed or failed on the current code.

Calculator Application Addition Functionality  ✓ adds 2 numbers together
✓ adds multiple numbers together
Subtraction Functionality ✓ subtracts the specified numbers3 passing (9ms)

Describe and It Keywords

Mocha uses the keyword describe in order to batch a test suite (group of tests relating to a single desired functionality). Then, it uses the keyword it in order to batch unit tests (singular descriptions of the desired behavior which can either pass or fail).

The first describe keyword takes 2 arguments, the name of the program being tested, and a function. That function is made up of each test suite, each described using another describe keyword. Each of those describe keywords take 2 arguments, a description of the functionality being tested, and a function. Finally, within those blocks, we use the it keyword to take in another 2 arguments. The first being a description of the unit test, the second being another function. That function body contains a “matcher”, A.K.A. an assertion (from the Chai library), which tests the expected behavior and allows for either a pass or fail.

const expect = require("chai").expect;
const calculator = require("../app/calculator");
describe("Calculator Application", function() {
describe("Addition Functionality", function() {
it("adds two numbers together", function() {
const total = calculator.add(2, 3);
expect(total).to.equal(5);
};
it("adds multiple numbers together", function() {
const total = calculator.add(1, 2, 3);
expect(total).to.equal(6);
});
});
... // other test suites here
}

Final Notes

Mocha can be effectively used for both front-end and back-end testing, but is stronger on the back-end. You can test asynchronous behaviors using promises or the async/await pattern. If you’d like to work with fake data and requests you can use a mock server like chai-http or other similar alternatives.

In order to use this testing most efficiently, the tests are generally written before the actual application code. This is in line with Behavior Driven Development (BDD) and makes sure that the outcome of your application produces the expected behaviors. The tests should be focused on the expected results, not upon the implementation of functionality. This produces applications that stand up to change, have predictable results, and few bugs.

--

--

Persis Randolph
Persis Randolph

Written by Persis Randolph

Full-Stack Developer based out of New Orleans, LA

No responses yet