39 lines
1.2 KiB
TypeScript
39 lines
1.2 KiB
TypeScript
import { Request, Response, NextFunction } from "express"
|
|
|
|
import {
|
|
authorizationMiddleware,
|
|
type AuthorizationRequest,
|
|
} from "@/middlewares/authorization-middleware"
|
|
|
|
import { User } from "@/models"
|
|
|
|
/**
|
|
* Usage:
|
|
* At the top level of a test file import:
|
|
* import { mockCurrentUser } from "@/support"
|
|
*
|
|
* Then where you want to set the current user:
|
|
* mockCurrentUser(currentUser)
|
|
*
|
|
* @param newCurrentUser - The user to set as the current user
|
|
*/
|
|
export function mockCurrentUser(newCurrentUser: User) {
|
|
vi.mock("@/middlewares/jwt-middleware", () => ({
|
|
default: async (_req: Request, _res: Response, next: NextFunction) => next(),
|
|
jwtMiddleware: async (_req: Request, _res: Response, next: NextFunction) => next(),
|
|
}))
|
|
|
|
vi.mock("@/middlewares/authorization-middleware")
|
|
const authorizationMiddlewareMock = vi.mocked(authorizationMiddleware)
|
|
authorizationMiddlewareMock.mockImplementation(
|
|
async (req: AuthorizationRequest, _res: Response, next: NextFunction) => {
|
|
const currentUser = await User.withScope(["asCurrentUser"]).findByPk(newCurrentUser.id, {
|
|
rejectOnEmpty: true,
|
|
})
|
|
|
|
req.currentUser = currentUser
|
|
next()
|
|
}
|
|
)
|
|
}
|