Lambda@EdgeのテストをJestで書く


概要

Lambda@Edge の単体テストを Jest で書いたときのメモ。今回書いたのは Lambda@Edge だけど、Lambda でも基本的には同じはず。Jest はシンプルで良いですね。

導入方法

導入したいディレクトリを作成して、そこで以下のコマンドを入力していく。Jest の導入はすごく簡単。

  • npm init
    • npm を初期化する
    • インタラクティブに設定項目を聞かれるので、お好みで設定
    • test command だけ jest と入力する
  • npm install -D jest
    • jest をインストールする

テスト対象ファイル

今回テストするファイルはこちら。Lambda@Edge のリクエストオリジンで動作させるような処理。

main.js
"use strict";

exports.handler = (event, context, callback) => {
  const request = event.Records[0].cf.request;

  // /hoge にアクセスしたら /index.html へ向き先を変える
  if (request.uri.indexOf("/hoge") === 0) {
    request.uri = "/index.html";
    callback(null, request);
    return;
  }

  callback(null, request);
};

テストファイル作成

テストファイルは XXX.spec.js または XXX.test.js で作成する。この Lambda では callback が最終的にどのように実行されたかをチェックしたいので、 jest.fn() でモック化して呼び出す。

main.spec.js
const { handler } = require("./main");

// Mockオブジェクトを作成
const getMockEvent = (request) => {
  return {
    Records: [
      {
        cf: { request },
      },
    ],
  };
};

describe("handlerのテスト", () => {
  it("/hoge は /index.html に変更される", () => {
    const event = getMockEvent({ uri: "/hoge" });
    const callback = jest.fn();
    handler(event, null, callback);
    expect(callback).toHaveBeenCalledWith(null, { uri: "/index.html" });
    expect(callback).toHaveBeenCalledTimes(1);
  });

  it("/foo は何もされない", () => {
    const event = getMockEvent({ uri: "/foo" });
    const callback = jest.fn();
    handler(event, null, callback);
    expect(callback).toHaveBeenCalledWith(null, { uri: "/foo" });
    expect(callback).toHaveBeenCalledTimes(1);
  });
});

実行結果

$ npm test                                                                                                                                                                                         

> jest

 PASS  ./main.spec.js
  handlerのテスト
    ✓ /hoge は /index.html に変更される (3 ms)
    ✓ /foo は何もされない (1 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.459 s
Ran all test suites.

aws-lambda-mock-context

ちなみに Lambda の context をモック化したい場合は、下記のライブラリを使うのがシンプルで良い。今回の例では context が必要なかったので null にしているが、これを使えば const ctx = context() だけでモックが作成できる。