Amazon AlexaAWS

alexa-conversationでAlexa Skillのテストをする

この記事は一人Alexa Skills Kit for Node.js Advent Calendar 2017の3日目の記事です。 alexa-conversationでAlexaの会話をシュミレートする alexa- […]

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

この記事は一人Alexa Skills Kit for Node.js Advent Calendar 2017の3日目の記事です。

alexa-conversationでAlexaの会話をシュミレートする

alexa-conversationはNode.jsで作られたAlexa向けのファンクションをテストできるライブラリです。

以下の例の様に、Intentベースで会話の流れをテストすることができます。

conversation(opts)
  .userSays('LaunchRequest')
  .plainResponse
  .shouldContain('サンプルスキルへようこそ。')
  .userSays('AMAZON.StopIntent')
  .plainResponse
  .shouldContain('またのご利用をお待ちしてます。')
  .end()

セットアップ

mochaが必要ですので、一緒にインストールしましょう。

$ npm install --save-dev alexa-conversation mocha

ついでにテスト対象のコードも用意しておきます。

'use strict'
const Alexa = require('alexa-sdk')
const handlers = {
  'LaunchRequest': function () {
    this.emit(':tell', 'サンプルスキルへようこそ。')
  },
  'AMAZON.StopIntent': function () {
    this.response.speak('さようなら')
    this.emit(':responseReady')
  }
}

module.exports.hello = (event, context, callback) => {
  alexa = Alexa.handler(event, context, callback)
  alexa.registerHandlers(handlers)
  alexa.execute()
}

テストを書く

テストを書く前に、以下の様に設定を行います。

// ライブラリの読み込み
const conversation = require('alexa-conversation')
// テスト対象のファイルの読み込み
const app = require('../index.js')

const opts = {
  name: 'Alexa Sample App', // テスト名()
  appId: 'your-app-id',     // アプリID(ダミーでOK))
  app: app,                 // テスト対象
  handler: app.handler      // 実行するプロパティ(この場合は、`exposts.handler = () => {...}`))
}

そのあと以下の様に会話の流れをIntentベースで書いていきましょう。

conversation(opts)
  .userSays('LaunchRequest')
  .plainResponse
  .shouldContain('サンプルスキルへようこそ。')
  .userSays('AMAZON.StopIntent')
  .plainResponse
  .shouldContain('またのご利用をお待ちしてます。')
  .end()

.userSays('SlotIntent', {slotOne: 'slotValue'})の様に書くことで、Slot(変数)を与えることもできます。

テストする

テスト自体はMochaでテストする感覚で実行できます。

$ ./node_modules/mocha/bin/_mocha test/*/*
  Conversation: Alexa Sample App
    User triggers: LaunchRequest 
      ✓ Alexa's plain text response should contain: サンプルアプリへようこそ。
    User triggers: AMAZON.StopIntent
      1) Alexa's plain text response should contain: またのご利用をお待ちしてます
  21 passing (33ms)
  1 failing

  1) Conversation: Alexa Sample App
       User triggers: LaunchRequest 
         Alexa's plain text response should contain: またのご利用をお待ちしてます。:
     AssertionError: expected ' さようなら ' to include 'またのご利用をお待ちしてます。'
      at Context.it (node_modules/alexa-conversation/response.js:100:32)

AMAZON.StopIntentで「またのご利用をお待ちしてます。」という発話を期待しているのに、「さようなら」と返ってきていることが発覚しました。

使い所

Intentベースで会話の流れをシュミレートできますので、振る舞い駆動的に開発したい場合におすすめかなと思います。
反面eventの値を細かくシュミレートすることはできませんので、そういったテストについては自力でユニットテストを書くことをおすすめします。

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

WP Kyotoサポーター募集中

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

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

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

Related Category posts