Skip to content

Commit d62c539

Browse files
committedDec 3, 2024
add tests for auth middleware
1 parent c892c71 commit d62c539

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
 

‎test/middleware/is-auth.test.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
const jwt = require("jsonwebtoken");
2+
3+
const isAuth = require("../../middleware/is-auth");
4+
const { throwError } = require("../../util/error");
5+
6+
jest.mock("jsonwebtoken");
7+
jest.mock("../../util/error");
8+
9+
describe("Auth Middleware", () => {
10+
let req, res, next;
11+
12+
beforeEach(() => {
13+
req = {
14+
get: jest.fn(),
15+
};
16+
res = {};
17+
next = jest.fn();
18+
throwError.mockImplementation((statusCode, message, next) => {
19+
const error = new Error(message);
20+
error.statusCode = statusCode;
21+
next(error);
22+
});
23+
});
24+
25+
it("should throw an error if no authorization header is present", () => {
26+
req.get.mockReturnValueOnce(null);
27+
28+
isAuth(req, res, next);
29+
30+
expect(throwError).toHaveBeenCalledWith(401, "Unauthorized", next);
31+
});
32+
33+
it("should throw an error if the token is invalid", () => {
34+
req.get.mockReturnValueOnce("Bearer invalidtoken");
35+
jwt.verify.mockImplementationOnce(() => {
36+
throw new Error("Invalid token");
37+
});
38+
39+
isAuth(req, res, next);
40+
41+
expect(throwError).toHaveBeenCalledWith(401, "Invalid token", next);
42+
});
43+
44+
it("should set userId on the request if the token is valid", () => {
45+
req.get.mockReturnValueOnce("Bearer validtoken");
46+
jwt.verify.mockReturnValueOnce({ userId: "abc123" });
47+
48+
isAuth(req, res, next);
49+
50+
expect(req.userId).toBe("abc123");
51+
expect(next).toHaveBeenCalled();
52+
});
53+
});

0 commit comments

Comments
 (0)
Please sign in to comment.