Testing
This page is a work in progress. If you want to help us to make this page better, please consider contributing on GitHub.
As of Middy v3, by default it will trigger an Abort signal shortly before a lambda times out to allow your handler to safely stop up and middleware to clean before the lambda terminates. When writing tests for lambda handlers wrapped with middy you'll need to account for this. There are a few approaches:
- Set
middy(handler, { timeoutEarlyInMillis: 0 })
to alternatively disable the creation of the AbortController. - Set
middy(handler, { timeoutEarlyResponse: () => {} })
to disable the timeout error from being thrown using a no-op. - Set
context.getRemainingTimeInMillis = falsy
to disable the creation of the AbortController.
When using Middy cache
and cacheExpiry
in unit tests for functions in your code, it is important to conditionally disable them for test cases by setting both Middy options
fields as follows:
{
cache: false,
cacheExpiry: 0,
...
}
Failing to do so may make the tests end with unfinished worker processes. Although they may still succeed, this can cause issues and timeout errors, namely in CI/CD environments.
An example of a message generated by Jest unit tests and which signals the need for this is as follows:
A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.
jest and typescript
If you use middy v5+, jest and typescript, and use ts-jest as a transformer, then you need to ensure that middy modules are not transformed. Use this in your jest.config.ts file
const esModules = ["@middy"].join("|")
const jestConfig: JestConfigWithTsJest = {
...
transform: {
"^.+\\.ts?$": [
"ts-jest",
{
useESM: true
}
]
},
transformIgnorePatterns: [`node_modules/(?!${esModules})`],
...
}
export default jestConfig
You must also use the flag --experimental-vm-modules
when running jest - eg have this in your package.json file
{
...
"scripts": {
...
"test": "NODE_OPTIONS=--experimental-vm-modules jest",
...
},
...
}
See https://kulshekhar.github.io/ts-jest/docs/guides/esm-support/ and https://jestjs.io/docs/ecmascript-modules for more details