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

How to test Middy handler with mocked middleware using Jest? #1272

Open
jgilewski-kone opened this issue Feb 4, 2025 · 2 comments
Open

How to test Middy handler with mocked middleware using Jest? #1272

jgilewski-kone opened this issue Feb 4, 2025 · 2 comments

Comments

@jgilewski-kone
Copy link

Hi,

I have a folloiwng handler:

export const handler = middy()
  .use(captureLambdaHandler(tracer))
  .use(injectLambdaContext(logger))
  .use(httpEventNormalizer())
  .use(httpHeaderNormalizer())
  .use(
    jsonBodyParser({
      disableContentTypeError: true, // Skip throwing 415 when Content-Type is invalid
    }),
  )
  .use(httpSecurityHeaders())
  .use(httpErrorHandler())
  .use(
    ssm({
      fetchData: {
        EXAMPLE_PARAM_VALUE: env.AWS_PARAMETER_STORE_EXAMPLE_PARAM,
      },
      setToContext: true,
      cache: false, // Switch off for tests
      //cacheExpiry: 15 * 60 * 1000,
    }),
  )
  .handler(lambdaHandler);

and I would like to test the handler mocking .use(ssm({...})) with jest.

First I was fighting with Jest and ESM module setup and I finally I get to the point where I was thinking to mock getInternal function in the following way:

import { jest } from "@jest/globals";
import { APIGatewayProxyEventV2, Context } from "aws-lambda";

const getInternal = jest.fn();
jest.unstable_mockModule("@middy/util", () => ({
  // eslint-disable-next-line @typescript-eslint/no-empty-object-type
  ...(jest.requireActual("@middy/util") as {}),
  getInternal,
}));

import { handler } from "../handler";

const createMockEvent = (
  data?: Partial<APIGatewayProxyEventV2>,
): APIGatewayProxyEventV2 => {
...
};

describe("MiddyRouter", () => {
  test("handler", async () => {
    const event = createMockEvent();
    const context = {} as never;

    getInternal.mockResolvedValue({
      EXAMPLE_PARAM_VALUE: "exampleValue",
    } as never);

    const result = await handler(event, context);

    expect(result).toEqual({});
  });
});

But from this error, it looks like the original implementation of getInternal is called (not my mock). I have no idea why.

    Error: Failed to resolve internal values
        at getInternal (/Users/jgi/Development/my_project/node_modules/@middy/util/index.js:83:11)
        at processTicksAndRejections (node:internal/process/task_queues:105:5)
        at async ssmMiddlewareBefore (/Users/jgi/Development/my_project/node_modules/@middy/ssm/index.js:181:20)
        at async runMiddlewares (/Users/jgi/Development/my_project/node_modules/@middy/core/index.js:230:17)
        at async runRequest (/Users/jgi/Development/my_project/node_modules/@middy/core/index.js:154:5)
        at async Object.<anonymous> (/Users/jgi/Development/my_project/lambdas/middy-router/src/__tests__/handler.test.ts:76:20) {
      [cause]: { package: '@middy/util', data: [ [CredentialsProviderError] ] }
    }

Do you guys have any example how to properly test Middy handler with mocking selected use middleware?
Any help and examples will be much appreciated.

Best wishes
JGI

@jgilewski-kone jgilewski-kone changed the title How to test Middy handler with mocking middleware using Jest? How to test Middy handler with mocked middleware using Jest? Feb 4, 2025
@willfarrell
Copy link
Member

Sorry to hear you're having troubles. I don't personally use jest, so I can't help there. But, if you take a look at the unit tests for middlewares like ssm, you'll see that the tests mock the AWS Client using aws-sdk-client-mock.

@jgilewski-kone
Copy link
Author

I tried that too. ssm midleware is initializing the middleware in the tests so they can provide mocked AwsClient (as here) from aws-sdk-client-mock.
My ssm middleware is already configured in the handler I tested and is not using the mocked client.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants