DEV Community

Eyitayo Itunu Babatope
Eyitayo Itunu Babatope

Posted on • Edited on

Test Driven Development in NodeJS

Introduction

Testing in software is the step wise process that ensures your code does what it was written to do. A typical programmer's work flow is to come up with an algorithm, write the code, and run the code. If the program runs without an error, it is code well written. If otherwise, the programmer tries to fix the error using the error message as a guide. Then, run the program again, hoping the error has been fixed. Sometimes the error get fixed at the first attempt and sometimes it takes many attempt.

For few lines of code, this method of testing will do but as application scales, this method of testing becomes tedious and time-consuming. Hence, the need for automated testing. Though test-driven development might sound esoteric, something for the senior developers. In reality, testing can be automated using testing frameworks such as mocha and implemented with few lines of code.

Mocha is a popular JavaScript framework that organizes our tests and runs them for us. In this post, mocha framework will be used to organize the test and assert module of Nodejs will be used to compare test values.

Prerequisite: JavaScript, Nodejs.
Objective: To gain knowledge about using mocha testing framework.

Step 1: Install mocha using
npm install mocha -save
in your package.json change the test field to
"test":" mocha test.js"

In the root folder, create a test.js file.
There are two key functions in mocha

  1. describe(): it helps group similar tests together.
  2. it(): contains test code, this is where we run our test code. Other functions are the hooks, such as
  3. before()
  4. beforeEach()
  5. after()
  6. afterEach() Read more about mocha Mocha Framework here

The above are hooks you run before or after the test function. The implementation is shown in the example below. The before and after() hooks run once, while beforeEach and afterEach run before and after every it() .

Open the test.js file and import the assert module and any other module needed. See the example below.

import assert from "assert/strict";
import { describe } from "node:test";
import { Student } from "../model/schema.js";
import { connectToDb,conClose } from "../model/connection.js";

describe('CRUD test',function(){

before(function(){
 connectToDb()
})
it('document should save without an error', function(done){
    const result=  new Student({email:"eyitayo@yahoo.com",pwd:"Sep215"})
    result.save(done)

  })
it('collection should return length greater than 0',async function(){
  const result= await Student.find({})
  assert.notStrictEqual(result.length, 0)

})
it('document should update without an error', async function( ){
    const query= await Student.updateOne({email:"eyitt@yahoo.com"},{firstname:'eyitayo',lastname:'itunu',gender:'male'})
    const result= await Student.findOne({email:'eyitayo@yahoo.com'})
    assert.strictEqual(result.lastname,'itunu')

  })
after(function(){
    conClose()
})
})
Enter fullscreen mode Exit fullscreen mode

In the above example, the describe() has two parameters: a string that describes the test and a callback function. Inside the callback function is it(). It has two parameters: a string that describes the outcome and a callback function that contains the test code. The assert strict function is used to compare test values. Other assert functions are

  • assert.deepEqual()
  • assert.deepStrictEqual()
  • assert.notDeepEqual()
  • assert.notDeepStrictEqual()
  • assert.notEqual()

Read more about [assert module]( https://github.com/nodejs/node/blob/v19.0.1/lib/assert.js

To run the test, go to the terminal and type npm test, test result is shown below.

> lmsnj@1.0.0 test
> mocha test/test.js

# Subtest: CRUD test
ok 1 - CRUD test
  ---
  duration_ms: 0.0530164
  ...



connected to MongoDb successfully
  1) document should save without an error
  ✔ collection should return length greater than 0 (350ms)
  ✔ document should update without an error (1713ms)

  2 passing (5s)
  1 failing

  1) document should save without an error:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (C:\Users\USER\lmsnj\test\test.js)
      at listOnTimeout (node:internal/timers:559:17)
      at processTimers (node:internal/timers:502:7)



1..1
# tests 1
# pass 1
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 38.0393548
Enter fullscreen mode Exit fullscreen mode

The first test failed, while the other two passed and were marked accordingly.

Finally
Testing is an important aspect of software development. It ensures that the code does what it was written to do. Using a testing framework like mocha automates the process.

If you find this post interesting, like and comment.

Top comments (0)