How to write a unit test for serverless function in dynamodb using jest

Viewed 13

I wish to write a unit test for following code but I am not sure where to start and what to mock from the code,

I am totally new to unit testing for dynamodb so I have zero idea where to start writing a unit test

import { v4 as uuidv4 } from 'uuid';
import { dynamodb } from '../libs/dynamodb';
import { validate } from './validate';

export const create = (event, context, callback) => {
    const timestamp = new Date().getTime();
    const data = JSON.parse(event.body);
    const validation = validate(data);

    if (!validation.ok) {
        console.error('Validation Failed');
        callback(null, {
            statusCode: 400,
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': true,
            },
            body: "Couldn't create the connection. \n - " + validation.message,
        });
        return;
    }

    const params = {
        TableName: process.env.CONNECTIONS_TABLE ?? '',
        Item: {
            id: uuidv4(),
            providerName: data.providerName,
            apiKey: data.apiKey,
            apiSecret: data.apiSecret,
            search: data.search,
            attributes: data.attributes,
            createdAt: timestamp,
            updatedAt: timestamp,
        },
    };

    // write the connection to the database
    dynamodb.put(params, (error) => {
        // handle potential errors
        if (error) {
            console.error(error);

            callback(null, {
                statusCode: error.statusCode || 501,
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Credentials': true,
                },
                body: "Couldn't create the connection.",
            });

            return;
        }

        // create a response
        const response = {
            statusCode: 200,
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': true,
            },
            body: JSON.stringify(params.Item),
        };
        callback(null, response);
    });
};

Please help me understand the procedure to write a unit test for this

Thank you

0 Answers
Related