Test Driven Development in NodeJS
Tags: node, webdev, javascript, express
Published: 2023-02-17 18:34:27

# Introduction

Testing in software is the step wise process that ensure your code does what it was written to do.  A typical programmer work flow is to come up with an algorithm, write the code, run the code. If the program runs without an error, it is a 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 organize our tests and run them for us. Though, it does not compare value in a test. In this post, mocha framework will be use 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 test together:
2 it(): contains test code , this is where we run our test code.
Other functions are the hooks such as
+ before()
+ beforeEach()
+ after()
+ afterEach()
Read more about mocha framework [here](https://mochajs.org/)

The above are hooks you run before or after the test function, 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 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()
})
})
```





 In the above example, the describe()  has  two parameter, a string that describes the test and a callback function. Inside the callback function is the it(). It has two parameters, a string that describes the out come, and a callback function that contains the test code. The assert strict function is use to compare test value. 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
```
The first test failed, while the the other two test 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 testing framework like mocha automate the process.

If you find this post interesting like and comment.