Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9409

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

$
0
0

概要

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)=>{constrequest=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オブジェクトを作成constgetMockEvent=(request)=>{return{Records:[{cf:{request},},],};};describe("handlerのテスト",()=>{it("/hoge は /index.html に変更される",()=>{constevent=getMockEvent({uri:"/hoge"});constcallback=jest.fn();handler(event,null,callback);expect(callback).toHaveBeenCalledWith(null,{uri:"/index.html"});expect(callback).toHaveBeenCalledTimes(1);});it("/foo は何もされない",()=>{constevent=getMockEvent({uri:"/foo"});constcallback=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()だけでモックが作成できる。


Viewing all articles
Browse latest Browse all 9409

Trending Articles