I have the following route:
router.post('/price-request/create', auth.middleware('jwt'), (req, res) =>
priceRequestController.create(req, res)
);
I need to test the controller, the controller has the following:
async create(req: Request, res: Response): Promise<void> {
const { sub: azUserObjectId } = req.authInfo as { sub: string };
const userTypeValue = await this.UserService.getUserType(azUserObjectId);
if (userTypeValue.isFailure) {
const codeError =
(userTypeValue && userTypeValue.getError()?.code) ||
httpStatus.INTERNAL_SERVER_ERROR;
res
.status(codeError)
.json({ errors: userTypeValue && userTypeValue.getError()?.message });
return;
}
const updatedBody = {
...req.body,
isToUpdate: false,
user_type: userTypeValue.getValue(),
created_by: azUserObjectId,
status: PriceRequestStatusEnum.DRAFT
};
const priceRequestDto = this.priceRequestMapper.rawToReqDto(updatedBody);
const errors = await validateDto(priceRequestDto);
if (errors.length > 0) {
res.status(httpStatus.BAD_REQUEST).json({ errors });
logger.warn(' Errors found in the request', errors);
return;
}
if (Array.isArray(priceRequestDto.email)) {
priceRequestDto.email = priceRequestDto.email.join(';');
}
const priceRequest = await this.PriceRequestService.createPriceRequest(
priceRequestDto
);
if (priceRequest && priceRequest.isSuccess) {
res.status(httpStatus.OK).send(priceRequest.getValue());
return;
}
const codeError =
(priceRequest && priceRequest.getError()?.code) ||
httpStatus.INTERNAL_SERVER_ERROR;
res
.status(codeError)
.json({ errors: priceRequest && priceRequest.getError()?.message });
}
But as you can see I have the route protected with a Middleware with passport, this is what it brings:
index.ts
import passport from 'passport';
import { authMiddleware, bearerStrategy } from './auth.middleware';
passport.use(bearerStrategy);
export default {
passportInstance: passport.initialize(),
middleware: authMiddleware
};
auth.middleware.ts
export const authMiddleware =
(authType: authType) => (req: Request, res: Response, next: NextFunction) => {
passport.authenticate(
authType,
{ session: false },
(
err: { message: any },
user: any,
info: Express.AuthInfo | undefined
) => {
if (err) {
return res
.status(httpStatus.UNAUTHORIZED)
.json({ error: err.message });
}
if (!user) {
return res
.status(httpStatus.UNAUTHORIZED)
.json({ error: 'Unauthorized' });
}
if (info) {
req.authInfo = info;
return next();
}
}
)(req, res, next);
};
Is there a way to stub and test my controller directly and omit the authentication middleware? and I need to send in the req the following attribute const { sub: azUserObjectId } = req.authInfo as { sub: string }; and I can think of doing it with chai-http, or is there a better way? Everythink is for the test with Mocha Chai and Sinon
Thank you very much
I am trying to find the best way to test my controller.