Mocking AWS SSM with Jest and TypeScript

Free sheep family image
Reading Time: < 1 minutes

Let’s say you have this code that uses SSM:

import { SSM } from 'aws-sdk';

const getSecureParameter = async (paramName: string): Promise<string | undefined> => {
    if (paramName.startsWith('/wrong')) throw new Error('wrong parameter');
    const ssm = new SSM();
    const secret = await ssm
        .getParameter({
            Name: paramName,
            WithDecryption: true,
        })
        .promise();
    return secret.Parameter ? secret.Parameter.Value : undefined;
};

export const getParam1 = () => getSecureParameter('/ssm/param/name/example');
export const getParam2 = () => getSecureParameter('/wrong/param');
export const getParam3 = () => getSecureParameter('/not/found/param');

To mock AWS SSM with Jest and TypeScript, you can use the AWS SDK’s mock implementation. Here’s how you can set it up:

import AWS from 'aws-sdk';
import { getParam1, getParam2, getParam3 } from '../mock';

jest.mock('aws-sdk');

const mockAws = AWS as jest.Mocked<any>;

const ssmMock = {
    getParameter: (options: AWS.SSM.Types.GetParameterRequest) => {
        return {
            promise: () => {
                switch (options.Name) {
                    case '/not/found/param': {
                        return Promise.reject(new Error('some error'));
                        break;
                    }
                    default: {
                        return Promise.resolve({
                            Parameter: {
                                Value: `mocked secret for ${options.Name}`,
                            },
                        });
                    }
                }
            },
        };
    },
};

describe('AWS SSM mock example tests', () => {
    beforeAll(() => {
        mockAws.SSM.mockImplementation(jest.fn().mockImplementation(() => ssmMock));
    });

    beforeEach(() => {
        //
    });

    it('should success when...', async () => {
        // example
        const result = await getParam1();
        expect(result).toBe('mocked secret for /ssm/param/name/example');
    });

    it('should fail due to some reason...', async () => {
        // example:
        await expect(getParam2()).rejects.toThrow(new Error('wrong parameter'));
    });

    it('should fail due to another reason...', async () => {
        // example:
        await expect(getParam3()).rejects.toThrow(new Error('some error'));
    });
});
, , ,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: