Home

Awesome

Description

Vitest e2e Test for serverless-aws-lambda

Requirements

Installation

yarn add -D serverless-aws-lambda-vitest
# or
npm install -D serverless-aws-lambda-vitest

Recommendations

Some recommendations to speed up Vitest e2e tests by avoiding double bundeling of your Lambdas by Vitest and serverless-aws-lambda.

Usage

use serverless-aws-lambda's defineConfig to import this plugin

// config.ts
import { defineConfig } from "serverless-aws-lambda/defineConfig";
import { vitestPlugin } from "serverless-aws-lambda-vitest";

const test = process.argv.includes("vitest");
const oneshot = process.argv.includes("run");

export default defineConfig({
  plugins: [
    test &&
      vitestPlugin({
        configFile: "./vitest.e2e.config.mts",
        oneshot,
        coverage: {
          outDir: "./coverage/",
          json: true,
          badge: true,
          threshold: 60,
        },
      }),
  ],
});
// vitest.e2e.config.mts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    include: ["tests/e2e/**/*.test.ts"],
  },
});

Run tests and watch for changes

make sure "sls": "sls" is defined in your package.json > scripts.

yarn sls aws-lambda -s dev vitest
# or
npm run sls -- aws-lambda -s dev vitest

Run tests in CI

yarn sls aws-lambda -s dev vitest run
# or
npm run sls -- aws-lambda -s dev vitest run

Testing async events

The plugin exposes multiple global functions to wait for Lambda handler async invokation responses.

Simple example of implementation for a SQS event:

import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";

const client = new SQSClient({
  region: "eu-west-3",
  endpoint: `http://localhost:${LOCAL_PORT}/@sqs`,
});

const cmd = new SendMessageCommand({
  QueueUrl: "MyQueueName",
  MessageBody: JSON.stringify({
    hello: {
      message: "world",
      firstVisit: true,
    },
  }),
});

test("Single SQS", async () => {
  const res = await client.send(cmd);
  const handlerResponse = await sqsResponse(res.MessageId);
  expect(handlerResponse.success).toBe(true);
});

see more examples.

Coverage

Supported events

Notes