Handing throw using jest and supertest

Viewed 467

I am trying to handle exception use case with supertest and jest for the given code. I tried many things but unable to find the solution.

var serverless = require('serverless-http');
import express from 'express';

const app = express();
app.use(express.json());

app.post('/post', async (req, res) => {

    try {
        // Get user from dynamodb
        const id = 'random-user-id';
        const user = await DynamoDb.Scan({
            TableName: 'user_table',
            FilterExpression: 'id = :id',
            ExpressionAttributeValues: {
                ':id': id,
            },
        }).catch(async (err) => {
            throw err;
        });

        console.log('user', user);
        return res.status(200).send();

    } catch (exception) {
        // Trying to handle this
        throw exception;
    }

});

module.exports.handler = serverless(app);

Test case

test("should throw error on failing to get user from database", async () => {

    mockScan.mockImplementation(() => {
        return {
            promise() {
                return Promise.reject({});
            },
        };
    });

    const response = await request
        .post(`/post`)
        .send();
});

On running the test, it is getting stuck and leading to

Jest did not exit one second after the test run has completed. This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.

0 Answers
Related