How to silence a method which is being called during HTTP unit test with chai and mocha

Viewed 103

I am testing a route which adds school bus to a school. Here's is my test module,

const chai = require("chai");
const chaiHTTP = require("chai-http");
const proxyquire = require("proxyquire");
const sinon = require("sinon");
const schoolBus = require("../../routes/schoolBus");

// Assertion style
chai.should();

chai.use(chaiHTTP);

let verifyToken;

// Transport Route test
describe("Transport Route", () => {
    const verifyStub = function () {
        return sinon.stub();
    };

    before(function () {
        verifyToken = proxyquire("../../routes/schoolBus", {
            verifyTokenPrincipalVicePrincipal: verifyStub,
        });
    });

    context("POST /add", () => {
        it("should add a school bus with validation information", () => {
            const bus = {
                name: "Alpha",
                route: "B/A",
                driverName: "Mike",
                driverPhone: "123456",
                price: 10,
            };

            chai.request(schoolBus)
                .post("/add")
                .send(bus)
                .end((err, response) => {
                    // response.should.have.status(200);
                    response.body.should.have.property("_id");
                    // response.body.should.have.property("name").eq("Alpha");
                    done();
                });
        });
    });
});

What I did here is, I tried to fake a module verifyToken which has a explicitly imported method verifyTokenPrincipalVicePrincipal in schoolBus module. This method checks for auth token in request header.

This is what I need to do actually. I have checked that test passes if this method is removed from the actual module and the module is required normally (without proxyquire).

Here's the route from the module,

router.post("/add", verifyTokenPrincipalVicePrincipal, async (req, res) => {
    try {
        // Validates request with Joi
        await schoolBusAddValidation(req.body);
        const bus = new Bus({
            name: req.body.name,
            route: req.body.route,
            driverName: req.body.driverName,
            driverPhone: req.body.driverPhone,
            price: req.body.price,
        });

        await bus.save();
        res.send(bus);
    } catch (err) {
        res.status(400).send({ message: err.details[0].message });
    }
});

Please help me with a comprehensive answer and give me some good resources on testing HTTP requests with Chai and Mocha which are discussed in detail.

Thank you.

0 Answers
Related