CMU Coding Bootcamp
at main 63 lines 1.5 kB view raw
1const { protect } = require("../middleware/authMiddleware"); 2const jwt = require("jsonwebtoken"); 3 4jest.mock("jsonwebtoken"); 5 6describe("Auth Middleware", () => { 7 it("should call next() with a valid token", () => { 8 jwt.verify.mockReturnValueOnce({ id: "user123" }); 9 10 const req = { 11 headers: { authorization: "Bearer valid-token" }, 12 }; 13 const res = {}; 14 const next = jest.fn(); 15 16 protect(req, res, next); 17 18 expect(next).toHaveBeenCalled(); 19 expect(req.user).toEqual({ id: "user123" }); 20 }); 21 22 it("should return 401 for a missing token", () => { 23 const req = { 24 headers: {}, 25 }; 26 const res = { 27 status: jest.fn().mockReturnThis(), 28 json: jest.fn(), 29 }; 30 const next = jest.fn(); 31 32 protect(req, res, next); 33 34 expect(res.status).toHaveBeenCalledWith(401); 35 expect(res.json).toHaveBeenCalledWith({ 36 message: "Not authorized, no token", 37 }); 38 expect(next).not.toHaveBeenCalled(); 39 }); 40 41 it("should return 401 for an invalid token", () => { 42 jwt.verify.mockImplementationOnce(() => { 43 throw new Error("Invalid token"); 44 }); 45 46 const req = { 47 headers: { authorization: "Bearer invalid-token" }, 48 }; 49 const res = { 50 status: jest.fn().mockReturnThis(), 51 json: jest.fn(), 52 }; 53 const next = jest.fn(); 54 55 protect(req, res, next); 56 57 expect(res.status).toHaveBeenCalledWith(401); 58 expect(res.json).toHaveBeenCalledWith({ 59 message: "Not authorized, invalid token", 60 }); 61 expect(next).not.toHaveBeenCalled(); 62 }); 63});