I’m doing the final exercise for Integration Testing. The first step is to test the PUT method for “should return 401 if client is not logged in” and I’m using the same code that Mosh provided but I keep getting this:
Here’s my code:
// Test PUT Method
describe("PUT /:id", () => {
let token;
let newName;
let genre;
let id;
const exec = async () => {
return await request(server)
.put("/api/genres/" + id)
.set("x-auth-token", token)
.send({ name: newName });
};
beforeEach(async () => {
// Before each test we need to create a genre and
// put it in the database.
genre = new Genre({ name: "genre1" });
await genre.save();
token = new User().generateAuthToken();
id = genre._id;
newName = "updatedName";
});
it("should return 401 if client is not logged in", async () => {
token = "";
const res = await exec();
expect(res.status).toBe(401);
});
});
router.delete("/:id", [auth, admin, validateObjectId], async (req, res) => {
const genre = await Genre.findByIdAndRemove(req.params.id);
if (!genre)
return res.status(404).send("The genre with the given ID was not found.");
res.send(genre);
});
In the testcase for trying delete an invalid id, expected response is 404. But i get 500. Similarly the testcase for put also fails. Can you @pfabbi help me figure out!
it(‘return error for deleting invalid id’, async () => {
id = 1;
const response = await delete_genre();
expect(response.status).toBe(404);
});
Also having the same issue with testing DELETE/:id endpoint. Expecting 404, receiving 500.
error: Cannot read properties of undefined (reading ‘id’)
Not sure why the same test for the put/:id endpoint is working fine (essentially the same test, but using findByIdAndRemove(…) instead of findByIdAndUpdate(…))