server: add basic jwt middleware tests
This commit is contained in:
parent
6c39d1c7c0
commit
0e57e28b6c
2 changed files with 49 additions and 1 deletions
48
server/src/lib/__tests__/middleware/jwt.ts
Normal file
48
server/src/lib/__tests__/middleware/jwt.ts
Normal file
|
@ -0,0 +1,48 @@
|
|||
import jwt, { UserJwtRequest } from "@lib/middleware/jwt"
|
||||
import { NextFunction, Response } from "express"
|
||||
|
||||
describe("jwt middlware", () => {
|
||||
let mockRequest: Partial<UserJwtRequest>
|
||||
let mockResponse: Partial<Response>
|
||||
let nextFunction: NextFunction = jest.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
mockRequest = {}
|
||||
mockResponse = {
|
||||
sendStatus: jest.fn().mockReturnThis(),
|
||||
}
|
||||
})
|
||||
|
||||
it("should return 401 if no authorization header", () => {
|
||||
const res = mockResponse as Response
|
||||
jwt(mockRequest as UserJwtRequest, res, nextFunction)
|
||||
expect(res.sendStatus).toHaveBeenCalledWith(401)
|
||||
})
|
||||
|
||||
it("should return 401 if no token is supplied", () => {
|
||||
const req = mockRequest as UserJwtRequest
|
||||
req.headers = {
|
||||
authorization: "Bearer"
|
||||
}
|
||||
jwt(req, mockResponse as Response, nextFunction)
|
||||
expect(mockResponse.sendStatus).toBeCalledWith(401)
|
||||
})
|
||||
|
||||
// it("should return 401 if token is deleted", async () => {
|
||||
// try {
|
||||
// const tokenString = "123"
|
||||
|
||||
// const req = mockRequest as UserJwtRequest
|
||||
// req.headers = {
|
||||
// authorization: `Bearer ${tokenString}`
|
||||
// }
|
||||
// jwt(req, mockResponse as Response, nextFunction)
|
||||
// expect(mockResponse.sendStatus).toBeCalledWith(401)
|
||||
// expect(mockResponse.json).toBeCalledWith({
|
||||
// message: "Token is no longer valid"
|
||||
// })
|
||||
// } catch (e) {
|
||||
// console.log(e)
|
||||
// }
|
||||
// })
|
||||
})
|
|
@ -17,7 +17,7 @@ export default async function authenticateToken(
|
|||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const authHeader = req.headers["authorization"]
|
||||
const authHeader = req.headers ? req.headers["authorization"] : undefined
|
||||
const token = authHeader && authHeader.split(" ")[1]
|
||||
|
||||
if (token == null) return res.sendStatus(401)
|
||||
|
|
Loading…
Reference in a new issue