Last active
August 24, 2022 22:16
-
-
Save HoukasaurusRex/3eb1720bbba1726bc4eeafde11a971a9 to your computer and use it in GitHub Desktop.
Dynamoose Mock Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { mockClient } from 'aws-sdk-client-mock' | |
import { PutItemCommand, GetItemCommand, QueryCommand, DeleteItemCommand } from '@aws-sdk/client-dynamodb' | |
import { marshall } from '@aws-sdk/util-dynamodb' | |
import * as dynamoose from 'dynamoose' | |
export type Item = Record<string, string | boolean | number> | |
export interface IMockDynamooseOptions { | |
item?: Item, | |
rejects?: boolean | |
} | |
const ddb = dynamoose.aws.ddb() | |
export const dynamooseMock = mockClient(ddb) | |
export const defaultDynamooseItem: Item = { | |
pk: 'pk', | |
sk: 'sk', | |
createdAt: new Date().toISOString(), | |
updatedAt: new Date().toISOString(), | |
updatedBy: 'updatedBy', | |
} | |
export const mockDynamoosePutItem = ({ item, rejects }: IMockDynamooseOptions = { item: {}, rejects: false }) => { | |
if (rejects) return dynamooseMock.on(PutItemCommand).rejects(new Error('PutItemCommand error')) | |
return dynamooseMock.on(PutItemCommand).resolves({ | |
Attributes: marshall({ | |
...defaultDynamooseItem, | |
...item | |
}) | |
}) | |
} | |
export const mockDynamooseGetItem = ({ item, rejects }: IMockDynamooseOptions = { rejects: false }) => { | |
if (rejects) return dynamooseMock.on(GetItemCommand).rejects(new Error('GetItemCommand error')) | |
return dynamooseMock.on(GetItemCommand).resolves({ | |
Item: item && marshall({ | |
...defaultDynamooseItem, | |
...item | |
}) | |
}) | |
} | |
export const mockDynamooseQuery = ({ item, rejects }: IMockDynamooseOptions = { rejects: false }) => { | |
if (rejects) return dynamooseMock.on(QueryCommand).rejects(new Error('QueryCommand error')) | |
return dynamooseMock.on(QueryCommand).resolves({ | |
Items: item && [marshall({ | |
...defaultDynamooseItem, | |
...item | |
})] | |
}) | |
} | |
export const mockDynamooseDeleteItem = ({ item, rejects }: IMockDynamooseOptions = { item: {}, rejects: false }) => { | |
if (rejects) return dynamooseMock.on(DeleteItemCommand).rejects(new Error('DeleteItemCommand error')) | |
return dynamooseMock.on(DeleteItemCommand).resolves({ | |
Attributes: marshall({ | |
...defaultDynamooseItem, | |
...item | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment