jeudi 19 novembre 2020

How to test a function (node module) if it's called with chai-spies / Mocha / Test

I want to test if a function is being called with chai-spies.

This is the class I want to test

index.js

const express = require('express');
const router = express.Router();
const request = require('request');

router.post('/login',(req,res) => {

    const {username, password} = req.body;
    let login= {};
    login.username= username;
    login.password= password;
    try{

        request.post({    // <---- this is the function I want to test if its called
            header: {'Content-Type': 'application/json-patch+json', 'accept ': 'application/json'},
            url: ' https://exmple',
            json: login
        }, function (error, response, body) {
            // implementation
        });
        } catch (error) {
    console.log(error);
}
});
module.exports = router;

and below is my test file i tried to write

index.test.js

const route = require ("../routes/index");
const spy = chai.spy.on(route,'request');
const request = require("supertest");
const express = require("express");
const bodyParser = require('body-parser');
const chai = require('chai');
let spies = require('chai-spies');
chai.use(spies);
const expect = chai.expect;

//create app without credentials
let app = express();
    app.use(express.urlencoded({ extended: false }));
    app.set('view engine', 'ejs');
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(route);

describe("Testing the POST /login route", () => {

let spy = chai.spy.on(route,'request'); // I tried to mock the function here with chai spies.

 it('should make a request to backend server when form is filled, but with wrong credentials', (done) => 
 {
        request(app)
            .post('/login')
            .set('Accept', 'application/json')
            .send({username:"test",password:"test"})
            .end(function (err,res) {   
                expect(spy).to.have.been.called.once;
                done();
            });
    });
});

As you can see i tried to mock the request function with chai spies let spy = chai.spy.on(route,'request');

but when I run the code it does recognize the mocking function and return

Uncaught AssertionError: expected { Spy 'object.request' } to have been called once but got 0
    + expected - actual

    -0
    +1

How can I test the request function if it is called. The request is actually a node module to make a http call on another backend server.

Thanks for your help.

Aucun commentaire:

Enregistrer un commentaire