Navigate back to the homepage

Testing Node API with Mocha & Chai

Ezekiel Ekunola
August 22nd, 2019 · 1 min read

What is Mocha?

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.

  • Synchronous Test Example
1it("two plus two is four", () => {
2 expect(2 + 2).to.equals(4);
3});
  • Asyncronous Test Code
1it("adds 2 numbers", done => {
2 // perform asynchronous actions
3 // write tests
4 done(); // call the done function after test.
5});

What is Chai?

Chai is a BDD (Behaviour-Driven Development) / TDD (Test-Driven Development) assertion library for nodejs and the browser that can be delightfully paired with any javascript testing framework.

Assertion Types

Chai has several interfaces from which developers can choose from. They are:

1chai.should();
2foo.should.be.a("string");
3foo.should.equal("bar");
4foo.should.have.lengthOf(3);
5tea.should.have.property("flavors").with.lengthOf(3);
1var expect = chai.expect;
2expect(foo).to.be.a("string");
3expect(foo).to.equal("bar");
4expect(foo).to.have.lengthOf(3);
5expect(tea)
6 .to.have.property("flavors")
7 .with.lengthOf(3);
1var assert = chai.assert;
2assert.typeOf(foo, "string");
3assert.equal(foo, "bar");
4assert.lengthOf(foo, 3);
5assert.property(tea, "flavors");
6assert.lengthOf(tea.flavors, 3);

Server Test

Now, I would be taking us through the process of setting up a basic Node API and writing tests for it.

First thing is to create our project folder and initialize it with npm to generate the package.json file.

1npm init -y

Install dependencies by running the commands below on your terminal

1npm i express --save
2npm i mocha chai chai-http --save-dev

Setup Server

Create an app.js file in the root of your project and add code below to create a server with express and also endpoints that we would be testing.

1const express = require("express");
2
3const app = express();
4
5app.use(express.json());
6
7app.get("/", (req, res) => {
8 res.json({ status: "success", message: "Welcome To Testing API" });
9});
10
11app.post("/add", (req, res) => {
12 const { num1, num2 } = req.body;
13 const add = (num1, num2) => {
14 return num1 + num2;
15 };
16 res.json({
17 status: "success",
18 result: "Welcome To Testing API",
19 result: add(num1, num2)
20 });
21});
22
23const PORT = process.env.PORT || 3000;
24
25app.listen(PORT, () => console.log(`App listening on port ${PORT}`));
26
27module.exports = app;

Setup Scripts

Add test script to package.json file.

1"scripts": {
2 "test": "mocha"
3 }

Write Tests

Create a test directory in your project, and then create an app.test.js file inside the test directory created.

Note: The reason we’re adding our tests to the test directory is that mocha searches for a test directory in your project by default, although this can be configured to suit your style. Find more here.

Then add code below

1const app = require("../app");
2const chai = require("chai");
3const chaiHttp = require("chai-http");
4
5const { expect } = chai;
6chai.use(chaiHttp);
7describe("Server!", () => {
8 it("welcomes user to the api", done => {
9 chai
10 .request(app)
11 .get("/")
12 .end((err, res) => {
13 expect(res).to.have.status(200);
14 expect(res.body.status).to.equals("success");
15 expect(res.body.message).to.equals("Welcome To Testing API");
16 done();
17 });
18 });
19
20 it("adds 2 numbers", done => {
21 chai
22 .request(app)
23 .post("/add")
24 .send({ num1: 5, num2: 5 })
25 .end((err, res) => {
26 expect(res).to.have.status(200);
27 expect(res.body.status).to.equals("success");
28 expect(res.body.result).to.equals(10);
29 done();
30 });
31 });
32});

At this point, your folder structure should look like the image below

Folder Structure

To run the test, run the command below on your terminal.

1npm test

Once the test is run, if the test passes, you should get a successful response on your terminal like the example shown below

Success Test

…and if the test fails, an error response on your terminal like the example shown below

Error Test

Find the code used in this project on Github

Find more information on Mocha here

Find more information on Chai here

Conclusion

In this article, we have been able to look at setting up testing with Mocha and Chai and also writing tests for our Node API. I would be improving on this article and project to integrate a Continuous Integration tool called Travis-CI.

If you have any questions or feedback, please feel free to reach out on Twitter. Thanks for reading 🙏🏾.

More articles from easybuoy

Setting Up Node API with Typescript

I'll be taking us through the steps of setting up a basic Node API with typescript.

August 13th, 2019 · 1 min read

Deploying Node App to Heroku

Learn about deploying a node app to heroku.

July 4th, 2019 · 2 min read
© 2018–2020 easybuoy
Link to $https://twitter.com/easybuoyLink to $https://github.com/easybuoy/Link to $https://instagram.com/easybuoy19Link to $https://www.linkedin.com/in/easybuoy/