0

I am writing a test for a middleware protected route and I want to make use of sinon.stub to replace the middleware authentication but when I run the tests, I can see that the stub is being ignored. I have tried this solution and this but I keep getting the same error.

This is the middleware:

exports.isAdmin = (req, res, next) => {
  const payload = req.decoded;
  console.log("Role: ", payload.user.role);
  if (payload && payload.user.role === "Admin") {
    next();
  } else {
    return res.status(403).send("Access denied.");
  }
};

The test file:

import chai from "chai";
import chaiHttp from "chai-http";
import sinon from "sinon";
import { country } from "./addcountry-data";

let server;
let auth;
chai.should();

const { expect } = chai;
chai.use(chaiHttp);

describe("Admin user can add country", () => {
  beforeEach(() => {
    auth = require("../../../middlewares/isAdmin");
    sinon.stub(auth, "isAdmin").callsFake((req, res, next) => {
      console.log("Stubbed");
      return next();
    });
    server = require("../../../app");
  });

  afterEach(() => {
    auth.isAdmin.restore();
  });

  it("should allow user with admin role add a country", done => {
    chai
      .request(server)
      .post("/api/v1/admin/addcountry")
      .send(country)
      .end((err, res) => {
        expect(res).to.have.status(201);
        done();
      });
  });
});

The route where the middleware is used:

import { Router } from "express";
import adminController from "../controllers/addCountry";
import loggedIn from "../middlewares/loggedIn";
import auth from "../middlewares/isAdmin";

const router = Router();
router.post("/admin/addcountry", auth.isAdmin, adminController.addCountry);

export default router;

The error message:

TypeError: Cannot read property 'user' of undefined
    at exports.isAdmin (C:\Users\user\code-jammers-backend\src\middlewares\isAdmin.js:2:276)

Any help will be appreciated. Thanks.

Fiyin Akinsiku
  • 166
  • 2
  • 13

0 Answers0