-1

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?

user6680
  • 79
  • 6
  • 34
  • 78

1 Answers1

0

You can use jest.spyOn method to mock find function, mock it throws an Error

it('should return status 500 when failed to retrieve posts', async () => {
  const mockFind = jest.spyOn(Post, 'find'); // spy on find method of Post object
  mockFind.mockRejectedValue(new Error('Failed to retrieve posts')); // mock it throws an Error object

  const res = await exec();

  expect(res.status).toBe(500); // expect the status
  // expect something about the body here...
  mockFind.mockRestore(); // remember restore it to original logic
});
hoangdv
  • 15,138
  • 4
  • 27
  • 48
  • Do you know why I'm getting an error on ```new Error```? https://postimg.cc/94K3kj82 I put your answer in same describe block – user6680 Oct 30 '20 at 14:20
  • @user6680 maybe in `router.get` you did not catch error what been thrown by `Post.find` – hoangdv Oct 31 '20 at 03:09
  • Sorry for the late response. I still haven't got this working. My guess is it's not hitting the correct endpoint. Don't I have to somehow reference ```/all``` inside jest spy code somewhere since that's the REST path? – user6680 Nov 22 '20 at 20:49