I am new to Jest and unit testing, I have an express API deployed on serverless(Lambda) on AWS.Express api uses dynamodb for crud operations
Note:- my api is based out of express and not just plain node, because on jest website they are telling ways for plain nodejs
I am able to do unit test on express on the methods which doesnt use dynamodb.However it fails for the methods which are using dynamodb, as to my understanding this has something to do with dynamodb being remote, because the code present in app.js corresponds to dyanmo db which is hosted on aws using lambda.
How do I go about it?
Note:- my api is based out of express and not just plain node
const isUrl = require('is-url'); const AWS = require('aws-sdk'); const { nanoid } = require('nanoid/async'); const express = require('express'); const router = express.Router(); const dynamoDb = new AWS.DynamoDB.DocumentClient(); // URL from users router.post('/', async (req, res, next) => { // urlId contains converted short url characters generated by nanoid const urlId = await nanoid(8); const { longUrl } = req.body; // Veryfying url Format using isUrl, this return a boolean const checkUrl = isUrl(longUrl); if (checkUrl === false) { res.status(400).json({ error: 'Invalid URL, please try again!!!' }); } const originalUrl = longUrl; const userType = 'anonymous'; // user type for anonymous users const tableName = 'xxxxxxxxxxxxx'; // table name for storing url's const anonymousUrlCheckParams = { TableName: tableName, Key: { userId: userType, originalUrl, }, }; dynamoDb.get(anonymousUrlCheckParams, (err, data) => { const paramsForTransaction = { TransactItems: [ { Put: { TableName: tableName, Item: { userId: userType, originalUrl, convertedUrl: `https://xxxxxxxxxxxxxxxx/${urlId}`, }, }, }, { Put: { TableName: tableName, Item: { userId: urlId, originalUrl, }, ConditionExpression: 'attribute_not_exists(userId)', }, }, ], }; if (err) { console.log(err); res .status(500) .json({ error: 'Unknown Server Error, Please Trimify Again!' }); } else if (Object.keys(data).length === 0 && data.constructor === Object) { dynamoDb.transactWrite(paramsForTransaction, async (error) => { if (error) { // err means converted value as userId is repeated twice. console.log(error); res .status(500) .json({ error: 'Unknown Server Error, Please trimify again. ' }); } else { res.status(201).json({ convertedUrl: `https://xxxxxxxxxxxx/${urlId}`, }); } }); } else { res.status(201).json({ convertedUrl: data.Item.convertedUrl, }); } }); }); module.exports = router; my test.js
const request = require('supertest'); const app = require('../app'); test('Should convert url from anonymous user ', async () => { await request(app) .post('/anon-ops/convert') .send({ longUrl: 'https://google.com', }) .expect(201); });