Mocking AWS SSM with Jest and TypeScript

Mocking AWS SSM with Jest and TypeScript
Reading Time: 3 minutes

Mocking in software development offers several advantages, but one of the most important ones is the ability to isolate and control dependencies. Here are a few key advantages of mocking:

  1. Test Independence: By using mocks, you can test a specific unit of code in isolation, without relying on the behavior of external dependencies. This ensures that your tests are independent and not affected by changes in other parts of the system.
  2. Faster and Repeatable Testing: Mocking allows you to simulate the behavior of external components or services, making your tests faster and more repeatable. You can define specific responses or scenarios, which eliminates the need for time-consuming interactions with real components.
  3. Reduced Complexity: Mocking simplifies the testing process by removing the need to set up complex and often resource-intensive external dependencies. This leads to cleaner and more focused tests that are easier to understand and maintain.
  4. Improved Fault Isolation: Mocking helps identify and isolate faults within your codebase. By substituting external dependencies with mocks, you can pinpoint the source of errors or unexpected behavior more easily, making debugging and troubleshooting faster and more efficient.
  5. Parallel Test Execution: With mocks, you can run tests in parallel without worrying about conflicts or interdependencies between different components. This speeds up the test execution time and improves overall testing efficiency.

Overall, mocking enables developers to write robust, reliable, and efficient tests by allowing them to control the behavior of external dependencies. It promotes testability, enhances the development process, and helps deliver high-quality software.


This time let’s see an example about mocking AWS SSM

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'));
    });
});

Mocking in software development offers several advantages, with the ability to isolate and control dependencies being one of the most important. By using mocks, developers can test specific units of code in isolation, leading to test independence and faster, repeatable testing. Mocking also reduces complexity by eliminating the need for complex external dependencies, allowing for cleaner and more focused tests. Additionally, fault isolation is improved as mocking helps identify and isolate faults within the codebase. With mocks, tests can also be executed in parallel, improving overall testing efficiency.

In the example of mocking AWS SSM with Jest and TypeScript, the AWS SDK’s mock implementation is used. By setting up the mock implementation, developers can simulate the behavior of AWS SSM and test their code without relying on the actual AWS services. This allows for more controlled and reliable testing.

Overall, mocking enables developers to write robust, reliable, and efficient tests by allowing them to control the behavior of external dependencies. It promotes testability, enhances the development process, and helps deliver high-quality software. With the ability to isolate and control dependencies, developers can confidently test their code and ensure its functionality without being dependent on external factors.

, , ,

About the author

Andrés Canavesi
Andrés Canavesi

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


Join 22 other subscribers

Leave a Reply