I have an endpoint I am testing with Jest and Supertest.
'/',
[
requiresAuthentication(),
upload.fields([
{ name: 'background', maxCount: 1 },
{ name: 'logo', maxCount: 1 },
{ name: 'additionalResources', maxCount: 1 },
]),
body('name').isString().isLength({ min: 0, max: 255 }).exists(),
body('badgeIssuer').isString().isLength({ min: 0, max: 255 }).exists(),
body('badgeName').isString().isLength({ min: 0, max: 255 }).exists(),
body('headerColor').isString().isLength({ min: 0, max: 255 }).exists(),
body('bodyTextColor').isString().isLength({ min: 0, max: 255 }).exists(),
body('buttonBGColor').isString().isLength({ min: 0, max: 255 }).exists(),
body('buttonTextColor').isString().isLength({ min: 0, max: 255 }).exists(),
body('thankYouMessage').isString().isLength({ min: 0, max: 1024 }).exists(),
],
async (req: any, res: Response) => {
const errors = validationResult(req);
if (!errors.isEmpty() || !req.admin) {
return res.status(400).json({ errors: errors.array() });
}
const background =
req.files.background !== undefined ? req.files.background[0] : null;
const logo = req.files.logo !== undefined ? req.files.logo[0] : null;
const additionalResources =
req.files.additionalResources !== undefined
? req.files.additionalResources[0]
: null;
if (logo === null)
return res
.status(400)
.json({ errors: [{ msg: 'Logo is not provided' }] });
try {
if (Array.isArray(req.files)) throw new Error('Invalid uploads');
const {
name,
badgeIssuer,
badgeName,
headerColor,
bodyTextColor,
buttonBGColor,
buttonTextColor,
thankYouMessage,
}: Campaign = req.body;
const createCampaign = await prisma.campaign.create({
data: {
name,
background: background === null ? null : formatFile(background),
logo: formatFile(logo),
headerColor,
bodyTextColor,
buttonTextColor,
buttonBGColor,
badgeIssuer,
badgeName,
postcodeQuestion: 1,
thermometerQuestion: 'West Midlands',
wordcloudQuestion: 2,
additionalResources:
additionalResources === null
? null
: formatFile(additionalResources),
thankYouMessage,
editURL: '',
publicURL: '',
sheetId: '',
open: true,
createdAt: new Date(),
},
});
try {
const {
response: {
result: { editURL, publicURL, ssID: spreadsheetID },
},
} = await makeAGoogleForm(name, createCampaign.id.toString());
const updatedCampaign = await prisma.campaign.update({
where: { id: createCampaign.id },
data: {
editURL,
publicURL,
sheetId: spreadsheetID,
},
});
return res.json({
updatedCampaign,
});
} catch (err) {
await prisma.campaign.delete({
where: { id: createCampaign.id },
});
}
} catch (err) {
res.status(400).json({ errors: [{ msg: (err as Error).message }] });
}
}
);
In order to test it I am required to send a file and send json data, but .send and .attach do not work at the same time. Is there a work around this, or do I need to refactor the end point and test services separately? Just to be clear, I did not write the code here I am only testing it.
Aucun commentaire:
Enregistrer un commentaire