我正在为中间件受保护的路由编写测试,并且我想使用sinon.stub
来代替中间件身份验证,但是当我运行测试时,我看到存根已被忽略。我已经尝试过this solution和this,但仍然遇到相同的错误。
这是中间件:
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.");
}
};
测试文件:
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();
});
});
});
使用中间件的路径:
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;
错误消息:
TypeError: Cannot read property 'user' of undefined
at exports.isAdmin (C:\Users\user\code-jammers-backend\src\middlewares\isAdmin.js:2:276)
任何帮助将不胜感激。谢谢。