Testing Node API with Mocha & Chai

Testing Node API with Mocha & Chai

In this tutorial we are going to write a simple RESTful API with Node.js and use Mocha and Chai to write tests against it.

What is Mocha?

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

Synchronous Test Example

it('two plus two is four', () => {
expect(2 + 2).to.equals(4);
});

Asyncronous Test Code

it("adds 2 numbers", (done) => {
// perform asynchronous actions
// write tests
done(); // call the done function after test.
});

What is Chai?

Chaiis 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:

Should

chai.should();
foo.should.be.a('string');
foo.should.equal('bar');
foo.should.have.lengthOf(3);
tea.should.have.property('flavors').with.lengthOf(3);

Expect

var expect = chai.expect;
expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
expect(foo).to.have.lengthOf(3); expect(tea).to.have.property('flavors').with.lengthOf(3);

Assert

var assert = chai.assert;
assert.typeOf(foo, 'string');
assert.equal(foo, 'bar');
assert.lengthOf(foo, 3);
assert.property(tea, 'flavors');
assert.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 thepackage.jsonfile.

npm init -y

Install dependencies by running the commands below on your terminal

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

Setup Server

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

const express = require("express");


const app = express();


app.use(express.json());


app.get("/", (req, res) => {
res.json({ status: "success", message: "Welcome To Testing API" });
});


app.post("/add", (req, res) => {
 const { num1, num2 } = req.body;
 const add = (num1, num2) => {
return num1 + num2;
};
res.json({
status: "success",
result: "Welcome To Testing API",
 result: add(num1, num2)
});
});


const PORT = process.env.PORT || 3000;


app.listen(PORT, () => console.log(`App listening on port ${PORT}`));


module.exports = app;

Setup Scripts

Add test script topackage.jsonfile.

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

Write Tests

Create a test directory in your project, and then create anapp.test.jsfile inside thetestdirectory 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](https://mochajs.org/#the-test-directory "here*") Then add code below

const app = require("../app");
const chai = require("chai");
const chaiHttp = require("chai-http");


const { expect } = chai;
chai.use(chaiHttp);
describe("Server!", () => {
 it("welcomes user to the api", done => {
chai
 .request(app)
.get("/")
end((err, res) => {
expect(res).to.have.status(200);
expect(res.body.status).to.equals("success");
expect(res.body.message).to.equals("Welcome To Testing API");
 done();
});
});


 it("adds 2 numbers", done => {
chai
.request(app)
.post("/add")
 .send({ num1: 5, num2: 5 })
.end((err, res) => {
expect(res).to.have.status(200);
expect(res.body.status).to.equals("success");
expect(res.body.result).to.equals(10);
 done();
 });
 });
});

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

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

npm test 

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

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

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](https://mochajs.org/#the-test-directory "here*")> 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](https://mochajs.org/#the-test-directory "here*")> 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](https://mochajs.org/#the-test-directory "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 about this article, feel free to leave a comment. Thanks for reading.

Further reading:

Real Time Apps with TypeScript: Integrating Web Sockets, Node & Angular

8 Miraculous Ways to Bolster Your React Apps

MEVN Stack Tutorial With Example From Scratch

Create Restful CRUD API with Node.js MongoDB and Express.js

Build a REST API to manage users and roles using Firebase and Node.js

A Guide to Node.js Logging

Build a Search Engine with Node.js and Elasticsearch

nodejs node javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Node canvas is a Cairo backed Canvas implementation for NodeJS.

node-canvas is a Cairo-backed Canvas implementation for Node.js.

What Is Nodejs Used For? | Nodejs Use Cases

A decade has passed since initial release of the node.js, it has gained immense popularity. Read in this article, what is nodejs used for? Nodejs Use Cases.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Hire NodeJs Developer

Looking to build dynamic, extensively featured, and full-fledged web applications? **[Hire NodeJs Developer](https://hourlydeveloper.io/hire-dedicated-node-js-developer/ "Hire NodeJs Developer")** to create a real-time, faster, and scalable...

Decoding Nodejs

The main goal of this blog is to explain the “Architecture of Nodejs” and to know how the Nodejs works behind the scenes. Generally, most of the server-side languages, like PHP, ASP.NET, Ruby, and including Nodejs follows multi-threaded architecture. That means for each client-side request initiates a new thread or even a new process.