I understand how to do a happy path and I have code coverage for all my happy paths, but I'm having trouble figuring out how to handle a catch
. I'm currently using supertest
So for example I have this API
router.get("/all", checkAuth, (req, res) => {
Post.find({}, { _id: 0 }).select('id title body _id userId').then((data) => {
status200("posts retrieved successfully", data, res)
}).catch((err) => {
status500(err, "failed to retrieve posts", res);
})
})
happy path example
describe('GET - /posts', () => {
const exec = async () => {
return await request(server)
.get('/api/posts/all')
.set('x-auth-token', token);
}
it('GETs posts and returns status 200', async () => {
const user = new User({
name: "John Smith",
email: "johnsmith@gmail.com"
});
await user.save();
const post1 = new Post({
title: "Title 1",
body: "body 1",
userId: user._id
});
const post2 = new Post({
title: "Title 2",
body: "body 2",
userId: user._id
});
await post1.save();
await post2.save();
const res = await exec();
expect(res.status).toBe(200);
expect(res.body.data.length).toBe(2);
expect(res.body.data.some(p => p.title === 'Title 2')).toBeTruthy();
expect(res.body).toHaveProperty('email', post2.email);
});
});
How can I write a JEST test for the catch block?