multicloud365
  • Home
  • Cloud Architecture
    • OCI
    • GCP
    • Azure
    • AWS
    • IAC
    • Cloud Networking
    • Cloud Trends and Innovations
    • Cloud Security
    • Cloud Platforms
  • Data Management
  • DevOps and Automation
    • Tutorials and How-Tos
  • Case Studies and Industry Insights
    • AI and Machine Learning in the Cloud
No Result
View All Result
  • Home
  • Cloud Architecture
    • OCI
    • GCP
    • Azure
    • AWS
    • IAC
    • Cloud Networking
    • Cloud Trends and Innovations
    • Cloud Security
    • Cloud Platforms
  • Data Management
  • DevOps and Automation
    • Tutorials and How-Tos
  • Case Studies and Industry Insights
    • AI and Machine Learning in the Cloud
No Result
View All Result
multicloud365
No Result
View All Result

The best way to write unit checks when utilizing the AWS JavaScript SDK v3?

admin by admin
April 3, 2025
in AWS
0
The best way to write unit checks when utilizing the AWS JavaScript SDK v3?
399
SHARES
2.3k
VIEWS
Share on FacebookShare on Twitter


Writing unit checks for code that interacts with the AWS JavaScript SDK v3 comes with two main advantages. Clearly, writing unit checks ensures you catch bugs early and due to this fact enhance the standard of your code. Additionally, writing unit checks lets you run your code domestically with out the necessity to attain out to the AWS service APIs. However how do you write unit checks for code interacting with the AWS JavaScript SDK v3?

How to write unit tests when using the AWS JavaScript SDK v3?

Within the following, I’ll share my learnings from writing unit checks by utilizing aws-sdk-client-mock by Maciej Radzikowski.

aws-sdk-client-mock is straightforward to make use of!

Let’s begin with a easy instance.

The next code snippet reveals the index.js file containing a handler() operate, which may very well be deployed as a Lambda operate. The handler() operate lists all buckets belonging to an AWS account.

import { S3Client, ListBucketsCommand } from '@aws-sdk/client-s3';

export async operate handler(occasion, context) {
const s3Client = new S3Client();
const response = await s3Client.ship(new ListBucketsCommand({}));
return response.Buckets;
}

So, how do I write a unit take a look at? I desire utilizing the take a look at framework mocha to put in writing JavaScript checks. The next snippet reveals the take a look at/take a look at.index.js file containing the skeleton to implement a take a look at.

import { deepStrictEqual } from 'node:assert';

import { handler } from '../index.js';

describe('demo', () => {
it('handler', async () => {
const now = new Date().toISOString();
const consequence = await handler({}, {});
deepStrictEqual(consequence, [{
Name: 'bucket-demo-1',
CreationDate: now
}])
});
});

When executing the take a look at, the handler() operate will ship a request to the S3 API. However doing so shouldn’t be possible for unit testing, as it is vitally difficult to make sure the response matches the assumptions within the unit take a look at.

As an alternative of sending requests to the AWS APIs use a typical testing method known as mocking. A mock simulates a dependency. So let’s mock the AWS Java Script SDK v3 by extending the take a look at/take a look at.index.js file.

import { S3Client, ListBucketsCommand } from '@aws-sdk/client-s3';
import { mockClient } from 'aws-sdk-client-mock';
import { deepStrictEqual } from 'node:assert';

import {handler} from '../index.js';

const s3Mock = mockClient(S3Client);

beforeEach(() => {
s3Mock.reset();
});

describe('demo', () => {
it('handler', async () => {
const now = new Date().toISOString();
s3Mock.on(ListBucketsCommand).resolvesOnce({
Buckets: [{
Name: 'bucket-demo-1',
CreationDate: now
}]
});
const consequence = await handler({}, {});
deepStrictEqual(consequence, [{
Name: 'bucket-demo-1',
CreationDate: now
}]);
});
});

Need to run the instance your self? Right here is the bundle.json that it’s essential to setup the instance.

{
"dependencies": {
"@aws-sdk/client-s3": "^3.583.0",
"aws-sdk-client-mock": "^4.0.0"
},
"title": "aws-mock-demo",
"model": "1.0.0",
"major": "index.js",
"devDependencies": {
"aws-sdk-client-mock": "^4.0.0",
"mocha": "^10.2.0"

},
"scripts": {
"take a look at": "mocha"
},
"kind": "module",
"writer": "",
"license": "ISC",
"description": ""
}

Lastly, run the take a look at.

The testing framework outputs the next outcomes.

> aws-mock-demo@1.0.0 take a look at
> mocha
demo
✔ handler

1 passing (5ms)

Subsequent, let me share a some classes discovered.

Making a mock with aws-sdk-client-mock

It took me a bit of bit to grasp that there are two methods to create a mock.

The next code creates a mock for a given shopper occasion.

const s3Client = new S3Client({});
const s3Mock = mockClient(s3Client);

Nevertheless, in lots of eventualities, you don’t have entry to the AWS SDK shopper cases. In these eventualities, right here is the way you globally mock a shopper.

const s3Mock = mockClient(S3Client);

The AWS JavaScript SDK v3 comes with built-in paginators. The next snippet reveals methods to web page via all gadgets saved in a DynamoDB desk.

import { DynamoDBClient, paginateScan } from '@aws-sdk/client-dynamodb';

const dynamodbClient = new DynamoDBClient();

export async operate handler(occasion, context) {
let consequence = '';
const paginator = paginateScan({
shopper: dynamodbClient
}, {
TableName: 'demo'
});
for await (const web page of paginator) {
consequence = consequence + web page.Objects[0].Information.S;
}
return consequence;
}

To put in writing a unit take a look at override the underlying command, ScanCommand on this instance.

import { DynamoDBClient, ScanCommand } from '@aws-sdk/client-dynamodb';
import { mockClient } from 'aws-sdk-client-mock';
import { deepStrictEqual } from 'node:assert';

const dynamodbMock = mockClient(DynamoDBClient);
import { handler } from '../index.js';

beforeEach(() => {
dynamodbMock.reset();
});

describe('demo', () => {
it('handler', async () => {
dynamodbMock.on(ScanCommand, {ExclusiveStartKey: undefined}).resolvesOnce({
Objects: [{Key: {S: '1'}, Data: {S: 'Hello '}}],
Rely: 1,
LastEvaluatedKey: {Key: {S: '1'}}
});
dynamodbMock.on(ScanCommand, {ExclusiveStartKey: {Key: {S: '1'}}}).resolvesOnce({
Objects: [{Key: {S: '2'}, Data: {S: 'World'}}],
Rely: 1,
LastEvaluatedKey: {Key: {S: '2'}}
});
dynamodbMock.on(ScanCommand, {ExclusiveStartKey: {Key: {S: '2'}}}).resolvesOnce({
Objects: [{Key: {S: '3'}, Data: {S: '!'}}],
Rely: 1
});
const consequence = await handler({}, {});
deepStrictEqual(consequence, 'Hiya World!');
});
});

Mocks vs. real-world

The tough half when writing mocks for the AWS SDK is to make sure comatiblity with the real-world. That’s why I don’t depend on unit testing. On prime of that, integration testing towards the AWS APIs is critical.

Abstract

aws-sdk-client-mock is a helpful device in relation to writing unit checks for code that interacts with the AWS JavaScript SDK v3. It has by no means been simpler to put in writing unit checks!

Tags: AWSJavaScriptSDKtestsunitWrite
Previous Post

Machine Predictive Upkeep with MLOps

Next Post

sqlmap Command-Line Cheat Sheet – Anto ./on-line

Next Post
sqlmap Command-Line Cheat Sheet – Anto ./on-line

sqlmap Command-Line Cheat Sheet - Anto ./on-line

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Trending

Plans, Critiques and Hidden Prices

Plans, Critiques and Hidden Prices

April 25, 2025
Progress Knowledge Cloud Accelerates Knowledge and AI Modernization with out Infrastructure Complexity

Augmenting Search with LLMs at Information Summit 2025

May 18, 2025
Prime 25+ AWS IAM Interview Questions and Solutions in 2024

Prime 25+ AWS IAM Interview Questions and Solutions in 2024

January 26, 2025
From a Level to L∞ | In the direction of Information Science

From a Level to L∞ | In the direction of Information Science

May 3, 2025
Well being Consciousness Fuels World Electrolyte Drinks Market Development

Well being Consciousness Fuels World Electrolyte Drinks Market Development

May 9, 2025
How I Would Be taught To Code (If I May Begin Over)

How I Would Be taught To Code (If I May Begin Over)

April 4, 2025

MultiCloud365

Welcome to MultiCloud365 — your go-to resource for all things cloud! Our mission is to empower IT professionals, developers, and businesses with the knowledge and tools to navigate the ever-evolving landscape of cloud technology.

Category

  • AI and Machine Learning in the Cloud
  • AWS
  • Azure
  • Case Studies and Industry Insights
  • Cloud Architecture
  • Cloud Networking
  • Cloud Platforms
  • Cloud Security
  • Cloud Trends and Innovations
  • Data Management
  • DevOps and Automation
  • GCP
  • IAC
  • OCI

Recent News

Closing the cloud safety hole with runtime safety

Closing the cloud safety hole with runtime safety

May 20, 2025
AI Studio to Cloud Run and Cloud Run MCP server

AI Studio to Cloud Run and Cloud Run MCP server

May 20, 2025
  • About Us
  • Privacy Policy
  • Disclaimer
  • Contact

© 2025- https://multicloud365.com/ - All Rights Reserved

No Result
View All Result
  • Home
  • Cloud Architecture
    • OCI
    • GCP
    • Azure
    • AWS
    • IAC
    • Cloud Networking
    • Cloud Trends and Innovations
    • Cloud Security
    • Cloud Platforms
  • Data Management
  • DevOps and Automation
    • Tutorials and How-Tos
  • Case Studies and Industry Insights
    • AI and Machine Learning in the Cloud

© 2025- https://multicloud365.com/ - All Rights Reserved