Below is the test function I have written:
describe("Test to Create a Problem", () => {
describe("Create a problem with valid input data", () => {
it("Should successfully create a problem", async () => {
const ProblemData = {
title: "Pothole on Main Street",
type: 2,
description: "Large pothole on Main Street that is causing damage to vehicles",
district: "Downtown",
coordinates: "42.3584,-71.0598",
address: "123 Main St, Boston, MA",
photos: JSON.stringify(["pothole1.jpg", "pothole2.jpg"]),
audio: "potholedowntown.mp4",
};
const payload = JSON.stringify(ProblemData);
console.log(payload);
await supertest(app)
.post(`/problems/create`)
.send(payload)
.expect(400)
.expect({
message: "Problem created."
});
});
});
});
The output from Jest is as follows:
> [email protected] test
> jest
console.log
{"title":"Pothole on Main Street","type":2,"description":"Large pothole on Main Street that is causing damage to vehicles","district":"Downtown","coordinates":"42.3584,-71.0598","address":"123 Main St, Boston, MA","photos":["photo1.jpg","photo2.jpg"],"audio":"potholedowntown.mp4"}
at src/tests/Problems.test.ts:60:17
FAIL src/tests/Problems.test.ts
Problems
Test to Create a Problem
Create a problem with valid input data
✕ Should successfully create a problem (79 ms)
● Problems › Test to Create a Problem › Create a problem with valid input data › Should successfully create a problem
expected { message: 'Problem created.' } response body, received {
message: 'Invalid request body.',
errors: [
"must have required property 'title'",
"must have required property 'description'",
"must have required property 'type'",
"must have required property 'district'",
"must have required property 'address'",
"must have required property 'coordinates'",
"must have required property 'audio'",
"must have required property 'photos'"
]
}
In the above code snippet, you can see that I logged the payload before sending it out. Strangely, when tested using Supertest, it does not work as expected.
The empty-field errors are due to the Ajv validator middleware. Here is the code snippet for the validator function:
export default function Validator(schema: object) {
return async (req: Request, res: Response, next: NextFunction) => {
let valid: boolean = false;
try {
valid = ajv.validate(schema, req.body);
} catch (err) {
Logger("FILE : Validator.ts \n" + String(err));
res.status(500).json({ message: "Internal Server Error" });
return;
}
if (!valid) {
let errors = ajv.errors;
let errMessages: (string | undefined)[] = [];
if (errors) {
errMessages = errors.map((error) => {
return error.message;
});
}
return res.status(400).json({
message: "Invalid request body.",
errors: errMessages
});
}
next();
};
}
I even logged the req.body
in the validator function and found it to be empty. Can someone explain why Supertest is failing to send the payload?