Node.js — Unit test case

Rafael Ragul A
YavarTechWorks
Published in
3 min readJun 26, 2020
Source (https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Node.js_logo.svg/1200px-Node.js_logo.svg.png)

Greetings everyone…

Today I would like to share, how I wrote unit test case for an application that follows a Service Layer Architecture. Following image gives you a glimpse of how that architecture looks like,

Source (https://martinfowler.com/eaaCatalog/ServiceLayerSketch.gif)

Target Audience,

Those who follows Service Layer Architecture and uses Sequelize ORM.

First things first, project source code and solution for test case can be found in GitLab — https://gitlab.com/ragul3/unit-test-case-1.git

Before we begin writing tests make sure to clone the repository which has simple CRUD APIs. Follow the README.md to setup the project

Test case dependencies,

  • Chai — An assertion library which can be paired with any JavaScript testing framework.
  • Mocha — JavaScript test framework running in Node.js and browser.
  • Nyc — Istanbul’s state of the art command line interface which provides code coverage of project.
  • Proxyquire — It proxies node.js require in order to make overriding dependencies easy during testing.
  • Sequelize test helpers — Helps in unit testing Sequelize models and code that needs those models.
  • Sinon — Standalone test spies, stubs and mocks for JavaScript.

Create directories,

  • In project root directory create test/unit/models and test/unit/services directories

Writing test for models,

test/unit/models/sample.model.js

In sample.model.js file,

  • We require sequelize-test-helpers which helps in testing models and the model which needs to be tested
  • checkModelName — Checks that a model is named correctly
  • checkPropertyExists — Checks that a model has the given properties

Writing test for services,

test/unit/services/sample.service.js

In sample.service.js file,

  • We require chai, sinon, proxyquire
  • Also we require makeMockModels from sequelize-test-helpers which helps in mocking the models
test/unit/services/sample.service.js
  • describe() — Is used to wrap a set of tests against one functionality
  • context() — Is used to wrap a set of tests against one functionality under same state
  • before() — Runs once at start of test
  • after() — Runs once at end of test
  • it() — Defines the test we need to test, expect is used to assert the actual and expected result
  • In SampleService variable, we require the actual service file using proxyquire and pass the mocked models
  • Also we stub the Sample.findAll() through sinon.stub() and resolve it with custom data

Once done run the test by typing in terminal as,

npm test

And from here I leave it on your own to write tests for Create, Update and Delete APIs.

In project root directory, solution for CRUD APIs are provided under unit-test-solution directory.

Thank you.

--

--