Amazon AlexaJavaScriptJestNode.js

Jest + Virtual AlexaでAlexaスキルのローカルテスト

Lambdaをinvokeした時のテストですが、2019年8月時点でのデファクトはVirtual Alexaかなと思います。 ということで2018年は違うことを言っていた気もしますが、Virtual Alexaでテストす […]

広告ここから
広告ここまで

Lambdaをinvokeした時のテストですが、2019年8月時点でのデファクトはVirtual Alexaかなと思います。

ということで2018年は違うことを言っていた気もしますが、Virtual Alexaでテストする方法をざっとまとめます。

セットアップ

npm からインストールしましょう。

$ npm i -D virtual-alexa jest
// TypeScriptの場合
$ npm i -D ts-jest @types/jest

Jestをランナーとして使うので、以下のようにファイルを配置します。

$ mkdir -p __tests__/integration
$ touch __tests__/integration/index.test.ts

また、package.jsonは以下のように記述しておきます。

  "scripts": {
    "test:integration": "jest __tests__/integration/*"

テストコードの配置

__tests__/integration/index.test.tsにテストコードを書いていきましょう。

import {VirtualAlexa} from 'virtual-alexa'
import { handler } from '../../index'

describe('test', () => {
  it("Accepts responses without dollars", async function () {
    const alexa = VirtualAlexa.Builder()
        .handler(handler)
        .interactionModelFile("../../models/ja-JP.json") 
        .create();
      alexa.dynamoDB().mock()

      const launchResponse = await alexa.launch();
      expect(launchResponse.response.outputSpeech.ssml).toContain( "Welcome to guess the price");
  })
})

interactionModelFileのパスに注意

ここで指定するパスは、テストを実行するディレクトリ(package.jsonのある場所)を基準とします。

importする時のノリで、テストコードの記述されたファイルからのパスのつもりで指定すると「ファイルがない」と怒られますので注意しましょう。

テストを実行する

あとはnpm run test:integrationでテストを実行しましょう。

    ✕ Accepts responses without dollars (88ms)

  ● test › Accepts responses without dollars

    expect(received).toContain(expected) // indexOf

    Expected substring: "Welcome to guess the price"
    Received string:    "<speak><p>サンプルゲームへようこそ!。</p><p>遊び方が知りたい場合は、「ヘルプ」と話しかけてください。。</p><p>早速ゲームを始めますか?</p></speak>"

      20 | 
      21 |       const launchResponse = await alexa.launch();
    > 22 |       expect(launchResponse.response.outputSpeech.ssml).toContain( "Welcome to guess the price");
         |                                                         ^
      23 |   })
      24 | })

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts