Mock AWS SDK for javascript / node.js in Jest

Windix Feng
2 min readJan 15, 2019

--

See my latest update on using ES6 destructing assignment at the end.

An example project can be found here: https://github.com/windix/jest-aws-sdk-mock

Take SSM.getParameter().promise() as an example.

Code:

const AWS = require('aws-sdk')

const ssm = new AWS.SSM()
const params = {
Name: 'NAME',
WithDecryption: true
}
const result = await ssm.getParameter(params).promise()

Test code:

const AWS = require('aws-sdk')

const ssmGetParameterPromise = jest.fn().mockReturnValue({
promise: jest.fn().mockResolvedValue({
Parameter: {
Name: 'NAME',
Type: 'SecureString',
Value: 'VALUE',
Version: 1,
LastModifiedDate: 1546551668.495,
ARN: 'arn:aws:ssm:ap-southeast-2:123:NAME'
}
})
})

AWS.SSM = jest.fn().mockImplementation(() => ({
getParameter: ssmGetParameterPromise
}))

Note: ES6 destructing assignment doesn’t work in this case (in both code and testing code). For example:

const { SSM } = require('aws-sdk')

We also use our own wrapper for AWS SDK at work. In our case, we don’t need to initialise new class with new AWS.SSM(), instead, using AWS.SSM(), but the above mock code still works.

Note that ES6 destructing assignment still doesn’t work in this case (in both code and testing code).

Update on 18/03/2019:

From my recent learning I realised ES6 destructing assignment SHOULD work! Please compare with the original code to see the differences!

Code:

const { SSM } = require('aws-sdk')const ssm = new SSM()
const params = {
Name: 'NAME',
WithDecryption: true
}
const result = await ssm.getParameter(params).promise()

Test code:

const { SSM } = require('aws-sdk')jest.mock('aws-sdk')const ssmGetParameterPromise = jest.fn().mockReturnValue({
promise: jest.fn().mockResolvedValue({
Parameter: {
Name: 'NAME',
Type: 'SecureString',
Value: 'VALUE',
Version: 1,
LastModifiedDate: 1546551668.495,
ARN: 'arn:aws:ssm:ap-southeast-2:123:NAME'
}
})
})

SSM.mockImplementation(() => ({
getParameter: ssmGetParameterPromise
}))

We need to use jest auto-mock jest.mock() which will set SSM = jest.fn() . So as long as we don’t reassign new value to SSM , instead, calling mockImplementation() on it directly and it will work perfectly.

--

--

Responses (4)