Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(parameters): add "testing your code" section #1383

Merged
merged 3 commits into from
Mar 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/snippets/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
"@aws-sdk/client-secrets-manager": "^3.250.0",
"@aws-sdk/client-ssm": "^3.245.0",
"@aws-sdk/util-dynamodb": "^3.245.0",
"aws-sdk-client-mock": "^2.0.1",
"aws-sdk-client-mock-jest": "^2.0.1",
"axios": "^1.2.4"
}
}
}
15 changes: 15 additions & 0 deletions docs/snippets/parameters/testingYourCodeClearCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { clearCaches } from '@aws-lambda-powertools/parameters';

describe('Function tests', () => {

beforeEach(() => {
jest.clearAllMocks();
});

afterEach(() => {
clearCaches();
});

// ...

});
15 changes: 15 additions & 0 deletions docs/snippets/parameters/testingYourCodeClientHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { getSecret } from '@aws-lambda-powertools/parameters/secrets';

export const handler = async (_event: unknown, _context: unknown): Promise<Record<string, unknown>> => {
try {
const parameter = await getSecret('my-secret');

return {
value: parameter
};
} catch (error) {
return {
message: 'Unable to retrieve secret',
};
}
};
41 changes: 41 additions & 0 deletions docs/snippets/parameters/testingYourCodeClientJestMock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { handler } from './testingYourCodeFunctionsHandler';
import {
SecretsManagerClient,
GetSecretValueCommand,
ResourceNotFoundException,
} from '@aws-sdk/client-secrets-manager';
import { mockClient } from 'aws-sdk-client-mock';
import 'aws-sdk-client-mock-jest';

describe('Function tests', () => {

const client = mockClient(SecretsManagerClient);

beforeEach(() => {
jest.clearAllMocks();
});

afterEach(() => {
client.reset();
});

test('it returns the correct error message', async () => {

// Prepare
client.on(GetSecretValueCommand)
.rejectsOnce(new ResourceNotFoundException({
$metadata: {
httpStatusCode: 404,
},
message: 'Unable to retrieve secret',
}));

// Act
const result = await handler({}, {});

// Assess
expect(result).toStrictEqual({ message: 'Unable to retrieve secret' });

});

});
9 changes: 9 additions & 0 deletions docs/snippets/parameters/testingYourCodeFunctionsHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';

export const handler = async (_event: unknown, _context: unknown): Promise<Record<string, unknown>> => {
const parameter = await getParameter('my/param');

return {
value: parameter
};
};
30 changes: 30 additions & 0 deletions docs/snippets/parameters/testingYourCodeFunctionsJestMock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { handler } from './testingYourCodeFunctionsHandler';
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';

jest.mock('@aws-lambda-powertools/parameters/ssm', () => ({
getParameter: jest.fn()
}));
const mockedGetParameter = getParameter as jest.MockedFunction<typeof getParameter>;

describe('Function tests', () => {

beforeEach(() => {
mockedGetParameter.mockClear();
});

test('it returns the correct response', async () => {

// Prepare
mockedGetParameter.mockResolvedValue('my/param');

// Act
const result = await handler({}, {});

// Assess
expect(result).toEqual({
value: 'my/param',
});

});

});
14 changes: 14 additions & 0 deletions docs/snippets/parameters/testingYourCodeProvidersHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { AppConfigProvider } from '@aws-lambda-powertools/parameters/appconfig';

const provider = new AppConfigProvider({
environment: 'dev',
application: 'my-app',
});

export const handler = async (_event: unknown, _context: unknown): Promise<Record<string, unknown>> => {
const config = await provider.get('my-config');

return {
value: config
};
};
33 changes: 33 additions & 0 deletions docs/snippets/parameters/testingYourCodeProvidersJestMock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { handler } from './testingYourCodeFunctionsHandler';
import { AppConfigProvider } from '@aws-lambda-powertools/parameters/appconfig';

describe('Function tests', () => {

const providerSpy = jest.spyOn(AppConfigProvider.prototype, 'get');

beforeEach(() => {
jest.clearAllMocks();
});

test('it retrieves the config once and uses the correct name', async () => {

// Prepare
const expectedConfig = {
feature: {
enabled: true,
name: 'paywall',
},
};
providerSpy.mockResolvedValueOnce(expectedConfig);

// Act
const result = await handler({}, {});

// Assess
expect(result).toStrictEqual({ value: expectedConfig });
expect(providerSpy).toHaveBeenCalledTimes(1);
expect(providerSpy).toHaveBeenCalledWith('my-config');

});

});
57 changes: 55 additions & 2 deletions docs/utilities/parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ By default, the provider will cache parameters retrieved in-memory for 5 seconds

You can adjust how long values should be kept in cache by using the param `maxAge`, when using `get()` or `getMultiple()` methods across all providers.

```typescript hl_lines="7 10" title="Caching parameters values in memory for longer than 5 seconds"
```typescript hl_lines="7 11" title="Caching parameters values in memory for longer than 5 seconds"
--8<-- "docs/snippets/parameters/adjustingCacheTTL.ts"
```

Expand Down Expand Up @@ -166,7 +166,7 @@ The AWS Systems Manager Parameter Store provider supports two additional argumen
| **decrypt** | `false` | Will automatically decrypt the parameter (see required [IAM Permissions](#iam-permissions)). |
| **recursive** | `true` | For `getMultiple()` only, will fetch all parameter values recursively based on a path prefix. |

```typescript hl_lines="6 8" title="Example with get() and getMultiple()"
```typescript hl_lines="6 9" title="Example with get() and getMultiple()"
--8<-- "docs/snippets/parameters/ssmProviderDecryptAndRecursive.ts"
```

Expand Down Expand Up @@ -397,3 +397,56 @@ The **`clientConfig`** parameter enables you to pass in a custom [config object]
```typescript hl_lines="2 4-5"
--8<-- "docs/snippets/parameters/clientConfig.ts"
```

## Testing your code

### Mocking parameter values

For unit testing your applications, you can mock the calls to the parameters utility to avoid calling AWS APIs. This can be achieved in a number of ways - in this example, we use [Jest mock functions](https://jestjs.io/docs/es6-class-mocks#the-4-ways-to-create-an-es6-class-mock) to patch the `getParameters` function.

=== "handler.test.ts"
```typescript hl_lines="2 4-7 12 18"
--8<-- "docs/snippets/parameters/testingYourCodeFunctionsJestMock.ts"
```

=== "handler.ts"
```typescript
--8<-- "docs/snippets/parameters/testingYourCodeFunctionsHandler.ts"
```

With this pattern in place, you can customize the return values of the mocked function to test different scenarios without calling AWS APIs.

A similar pattern can be applied also to any of the built-in provider classes - in this other example, we use [Jest spyOn method](https://jestjs.io/docs/es6-class-mocks#mocking-a-specific-method-of-a-class) to patch the `get` function of the `AppConfigProvider` class. This is useful also when you want to test that the correct arguments are being passed to the Parameters utility.

=== "handler.test.ts"
```typescript hl_lines="2 6 9 21"
--8<-- "docs/snippets/parameters/testingYourCodeProvidersJestMock.ts"
```

=== "handler.ts"
```typescript
--8<-- "docs/snippets/parameters/testingYourCodeProvidersHandler.ts"
```

In some other cases, you might want to mock the AWS SDK v3 client itself, in these cases we recommend using the [`aws-sdk-client-mock`](https://www.npmjs.com/package/aws-sdk-client-mock) and [`aws-sdk-client-mock-jest`](https://www.npmjs.com/package/aws-sdk-client-mock-jest) libraries. This is useful when you want to test how your code behaves when the AWS SDK v3 client throws an error or a specific response.

=== "handler.test.ts"
```typescript hl_lines="2-8 12 19 25-31"
--8<-- "docs/snippets/parameters/testingYourCodeClientJestMock.ts"
```

=== "handler.ts"
```typescript
--8<-- "docs/snippets/parameters/testingYourCodeClientHandler.ts"
```

### Clearing cache

Parameters utility caches all parameter values for performance and cost reasons. However, this can have unintended interference in tests using the same parameter name.

Within your tests, you can use `clearCache` method available in [every provider](#built-in-provider-class). When using multiple providers or higher level functions like `getParameter`, use the `clearCaches` standalone function to clear cache globally.

=== "handler.test.ts"
```typescript hl_lines="1 9-11"
--8<-- "docs/snippets/parameters/testingYourCodeClearCache.ts"
```
30 changes: 17 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.