MongoDB Module Setup – Node.js API with TDD Tutorial

After the Apps.js overview, let’s continue with the API codebase now with setting up the MongoDB Module. The API needs to persist the data to the MongoDB database, and since we brought up the MongoDB either by installing and running it locally or by starting it from the docker image, as described here, we would still add some scripts within the express application to connect to it when the node server startup.

As we have seen in the modular approach section, we will start writing the mongodb module files in the ‘mongodb’ directory. Let’s create the below files under each directory respectively. Then we will begin filling in with the appropriate scripts.

Module Files Setup

In this section, we will begin with setting up the files needed for mongodb module. Developing the MongoDB connection related scripts will be dealt with in the later part of this section with the TDD approach.

modules/mongodb directory

Under this directory, we will create the below two files for the MongoDB connection related scripts during the application startup.

  1. mongodb.module.js
  2. mongodb.util.js

1. mongodb.module.js file

This one is the main file for mongodb module. It is a unique object exposed as a javascript module. We can use this file to import any other modules declared within this module.

We can start with below code block in this file. It is called Immediately Invoked Function Expression (IIFE). I prefer this pattern to enclose the functional code inside the IFFE code block.

(function () {
    
})();

It is to restrict the internal variables to be accessible only inside this function and thus it provides privacy to these variables.

Next step would be to add the below statement within the IIFE block. What we are doing here is exporting an object via this module. So any types (a function or an object or a literal) will be exposed by this module. Other modules can ‘require‘ this module to use anything that’s revealed by this module to use those.

module.exports = {};

This the basic structure of the javascript file that we will create in this tutorial. We are declaring this as a strict mode as well with the second line.

(function () {
    'use strict';

    module.exports = {
        // Declare attributes here to be exposed to other modules
    };

})();

In a short time, we will continue with this file for more functional code along with TDD once we set up other files for this module.

2. mongodb.util.js file

It is where we will create the MongoDB connection creation functional code.  The primary content structure will be used for this file as well to begin as below.

(function () {
    'use strict';

    module.exports = {
        // Declare attributes here to be exposed to other modules
    };

})();

Test Files Setup

In this section, we will begin by setting up the files needed for testing the mongodb module. We will also go through the dependencies for test scripts and structure of those test script files.

Mocha is the testing framework that we will use here. It provides all the features to construct the unit or integration tests and also to run them. Run the below statement in the command line to include the mocha as a development dependency for this application. It will download and add the mocha library within the project and add the mocha in the package.json file as the development dependency.

npm install mocha --save-dev

As the unit test needs to assert the actual result of the test is the same as the expected result, we need an assertion library to do so.

Chai is one of the best assertion library available for Node. It has both a BDD (Behavior Driven Development) and TDD (Test Driven Development) style for assertions. We could use either one of them for our testing. We will use Chai for asserting the test results with BDD assertion style.

npm install chai --save-dev

It will download and add the chai library within the project and add the chai in the package.json file as the development dependency.

tests/unit/mongodb directory

To write unit tests for the above main files, we will need test files. There are many suggested naming convention for these test specification files. Let’s follow one of the naming conventions by prefixing the .specs before the .js as below. As these are unit test specification files, eventually we place them under tests/unit directory for the mongodb module.

  1. mongodb.module.specs.js
  2. mongodb.util.specs.js

As described in the Test Driven Development blog post, we will continue with the mongodb module development in TDD approach.

First, we will write the test scripts for the expected behaviour of the functional script and then write minimal code to pass the test that we just wrote. Repeating these steps will eventually result in the completion of the functional scripts in the main javascript files.

1. mongodb.module.spec.js file

To test the mongodb.module.js file, we will use this file. Unit tests for testing the main file’s behaviour will be written here.

Now, we have the test dependencies added, let’s jump onto the test scripts. We need to import or ‘require’ the assertion library and the BDD style as follows in the mongodb.module.spec.js file.

var chai = require('chai');
var expect = chai.expect;

We need to set up the test suites further in this file. A bunch of tests can be grouped into a single test suite to run them all at once. In Mocha, we will use the below code block as the test suite. 

describe('Can be a file/function/module name', function () {
});

The describe() contains two parameters: a name and a function that encapsulates the tests. We can also create a nested describe() blocks to run a bunch of test suites together.  

The scripts that test the behaviour of the main file is called specs which are shown in the below code. 

it('should describe the test and it’s expectation', function() {
});

As shown, the spec is defined by its code block, which consists of two parameters like describe, a string and a function. The first parameter can be a brief description of what that spec is testing to confirm the expected behaviour of that code block that’s being tested.

Inside this specs function, expectations should be defined to compare the actual result with an expected result to test the behaviour of the piece of code that’s under test. We will use the expect, a BDD style function of the chai assertion library,¬ for building the expectations to assert. Below code is the sample of an expectation.

expect(SomeModule).to.be.a('object');

So based on the above explanation of the test script file content, here is the mongodb.module.specs.js test file’s necessary content for the test suite.

var chai = require('chai');
var expect = chai.expect;

var MongoDBModule = require('../../../modules/mongodb/mongodb.module');

describe('MongoDBModule', function () {

    describe('mongodb.module file', function () {

        it('should test first behavior', function () {
            // Write expectations here for the behavior 
        });

    });

});

At line number 5, we are importing the mongodb.module.js to the test file so that we can test its behaviour. Further sections will cover the actual tests we will run through.

2. mongodb.util.spec.js file

To test the mongodb.util.js file, we will use this file. Unit tests for testing this file’s behaviour will be written here. Below is the initial content of this file begin with.

var chai = require('chai');
var expect = chai.expect;

var MongoDBUtil = require('../../../modules/mongodb/mongodb.util');

describe('MongoDBUtil', function () {

    describe('mongodb.util file', function () {

        it('should test first behavior', function () {
            // Write expectations here for the behavior 
        });

    });

});

MongoDB Configuration File Setup

To make a connection to the MongoDB, we would need to obtain the MongoDB connection parameters in the mongodb.util.js file. We will go over those scripts later in this section. Meanwhile, we could make a configuration file with the conniption details of the MongoDB server. 

Below is the configuration file that we will be using for our development. It could be made with environment specific so that different configuration file can be used based on the environment. Anyway, for this tutorial’s example, it’s out of the scope. Let’s continue with the development specific directory and file required for the configuration.

config/mongodb directory

Under the root directory of the application, create a directory config/mongodb with a file mongodb-config.json. We will be using the JSON format for configuring the MongoDB connection details. 

{
  "mongodb": {
    "server": "localhost:32769",
    "database": "customer_db_dev",
    "user": null,
    "password": null
  }
}

Here, the server attribute is the MongoDB URL that you might have noted down during the MongoDB server setup either via the direct installation or docker image. The database is the name of the database for this RESTful service. If you keep the user and password attributes as null, you do not need to create the database in the MongoDB server as it will be automatically created when the application is starting up.

Please check out the index page for this Node.js RESTful API development with TDD approach tutorial with all the posts in sequence in one place.

This blog post is an excerpt from the book Building Node.js REST API with TDD approach. Please check out the link for more information.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.