I tried to test my API using super test , but when I add a auth middleware , I don't know how to mock the middleware , here's my code.
authMiddleware.js
export const authMiddleware = async (req: RequestWithUser, res: Response, next: NextFunction) => {
try {
const Authorization = req.cookies['Authorization'] || req.header('Authorization').split('Bearer ')[1] || null;
if (Authorization) {
const secretKey: string = config.get('secretKey');
const verificationResponse = (await jwt.verify(Authorization, secretKey)) as DataStoredInToken;
console.log(verificationResponse);
const userId = verificationResponse._id;
const findUser = await userModel.findById(userId);
if (findUser) {
req.user = findUser;
next();
} else {
next(new HttpException(401, 'Wrong authentication token'));
}
} else {
next(new HttpException(404, 'Authentication token missing'));
}
} catch (error) {
next(new HttpException(401, 'Wrong authentication token'));
}
};
describe('[GET] /users/:id', () => {
it('response findOne User', async () => {
const userId = 'qpwoeiruty';
const usersRoute = new UsersRoute();
const users = usersRoute.usersController.userService.users;
users.findOne = jest.fn().mockReturnValue({
_id: 'qpwoeiruty',
email: 'a@email.com',
isAdmin: false,
password: await bcrypt.hash('q1w2e3r4!', 10),
});
(mongoose as any).connect = jest.fn();
const app = new App([usersRoute]);
return request(app.getServer()).get(`${usersRoute.path}/${userId}`).expect(200);
});
});
The above test failed duo to my request did not have authorization in header, and I think about set header , but when it comes to
const finder = await userModel.findById(userId);
this will fail since it is related to server action and real database , so I don't think that is the right way to write this test.
What I want to do is to mock my authMiddleware variable ,for example
const findUser = jest.fn().mockReturnValue(
....
)
so that the auth middleware can pass , what't the right way to do here?