-
Notifications
You must be signed in to change notification settings - Fork 40
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
Unable to mock "Top-Level" awaits AWS sdk calls #78
Comments
In ES modules all issue78.ts: console.log('handler file')
export const handler = async () => {
return '';
}; issue78.test.ts: console.log('before import handler');
import {handler} from '../src/issue78'
console.log('after import handler'); Prints:
This is in contrast to CommonJS, where So in fact the top-level await is called before we setup a mock in our test. A workaround is to setup the mock before our test file. In jest, you can do this with setupFilesAfterEnv configuration option. It would be like this: package.json: {
...
"jest": {
"testEnvironment": "node",
"setupFilesAfterEnv": [
"./test/setup.js"
]
}
} test/setup.js: import {mockClient} from 'aws-sdk-client-mock';
import {GetParameterCommand, SSMClient} from '@aws-sdk/client-ssm';
const snsMock = mockClient(SSMClient);
snsMock.on(GetParameterCommand).resolves({
Parameter: {Value: 'qq'}
}); I tested it and it works. The drawback is that you need to set it in a global setup file, and cannot change between test invocations. However, I don't see any other option, as those are the ES modules' constraints. I also did not find many examples of unit testing top-level await online. I'm open to any suggestions. I'm closing this since it's not a problem with the lib itself, and the solution above works. |
I was able to get this working by using import { vi } from 'vitest';
const mockSecretsManager = await vi.hoisted(async () => {
const { mockClient } = await import('aws-sdk-client-mock');
const { SecretsManager } = await import('@aws-sdk/client-secrets-manager');
return mockClient(SecretsManager);
}); Hopefully this helps! |
Amazon now recommends using top-level awaits for performance in lambdas.
https://aws.amazon.com/blogs/compute/using-node-js-es-modules-and-top-level-await-in-aws-lambda/
Unfortunately mocks do not work on "top-level awaits.
Example code from the amazon page linked above:
Simple test:
result:
CredentialsProviderError: Could not load credentials from any providers
The text was updated successfully, but these errors were encountered: