1 year ago

#367131

test-img

Neela

Jest unit test cases for NodeJs

I am new to Node.js and Jest unit test cases. I have tried to call Jest for controller.js. It is working for one endpoint for another endpoint the controller is making a call to service.

I have not used the mock. Direct call from Jest I have tried. But 'request.on' has not been covered from Jest. I tried all combinations but no luck. I am adding the code details below.

Please let me know how to call 'request.on' from Jest or how to make calls to Service using mock.

controller.js

'use strict'

const service = require('./service/serviceClass');

const control = {
  serve: (req, res) => {
    service.serve(req, res);
  },
}
module.exports = control;

serviceClass.js

require("dotenv").config();
const firebase = require('firebase-admin');
let fbMap = new Map();

function fbInit(){
   let fbAdmin = firebase.initializeApp({
      credential: firebase.credential.cert('service.json');
   });
   fbMap.set('fb', fbAdmin);
}

let serve = {

    serve: (req, res, next) => {
       fbInit();
       const body = [];
       req.on('data', (chunk) => body.push(chunk))
       req.on('end', () => {
             const reqString = Buffer.concat(body).toString();
             var id = JSON.parse(reqString).firebaseId;
             if(id !=== undefined){
            var fire = fbMap.get('fb');
                  fire.auth().getUser(id).then((user)=>{
                    if(user != null){
                     console.log("email of the user:"+user.email);
                 }
             )};
          }
        } 
    }
}

module.exports=serve;

It would be great if I get the help to either make 'mock' calls for service or how to make the code cover for 'request.on' from Jest.

javascript

node.js

unit-testing

jestjs

code-coverage

0 Answers

Your Answer

Accepted video resources