iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔥

Unit Testing Dialogflow Fulfillment Deployed to Firebase

に公開

Date created: 2019/06/26

I looked into how to test Firebase Functions used in Dialogflow.

Preparation

First, prepare the function like this:

const functions = require("firebase-functions")
const { WebhookClient } = require("dialogflow-fulfillment")

exports.dialogflowFirebaseFulfillment = functions.https.onRequest(
  (request, response) => {
    const agent = new WebhookClient({ request, response })
    const intentMap = new Map()
    function hello(agent) {
      const { name } = agent.parameters
      agent.add(`ハロー! ${name}`)
    }

    intentMap.set("hello", hello)
    agent.handleRequest(intentMap)
  }
)

Writing Tests

Write the test straightforwardly like this.
Since firebase-functions-test cannot be used, simply forge and pass req and res objects.
https://firebase.google.com/docs/functions/unit-testing?hl=en

If you want to be more thorough, you could use node-mocks-http, but I didn't go that far this time.

const assert = require("assert")
const { dialogflowFirebaseFulfillment } = require("../simple.js")

describe("function", () => {
  it("janken", (done) => {
    const req = {
      body: {
        queryResult: {
          queryText: "ハロー",
          parameters: {
            name: "太郎"
          },
          intent: {
            displayName: "hello"
          }
        }
      }
    }

    const res = {
      json: (j) => {
        console.log(j)
        const expect = { fulfillmentText: "ハロー! 太郎", outputContexts: [] }
        assert.deepEqual(expect, j)
        done()
      }
    }

    dialogflowFirebaseFulfillment(req, res)
  })
})

How to Build the Request?

By the way, it's a bit hard to notice, but you can perform input tests on the right side.

<blockquote class="twitter-tweet"><p lang="ja" dir="ltr">このTry it now入力できたのか!分かりづらい! <a href="https://t.co/BaRlsuYO74">pic.twitter.com/BaRlsuYO74</a></p>— @terrierscript <a href="https://twitter.com/terrierscript/status/1143808200359084033?ref_src=twsrc^tfw">June 26, 2019</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

Then, by clicking "DIAGNOSTIC INFO" and opening the "FULFILLMENT REQUEST" tab, you can obtain the JSON that comes into the API as a request. It's a good idea to create your data based on this.

<blockquote class="twitter-tweet" data-conversation="none" data-lang="ja"><p lang="ja" dir="ltr">しかし結果がすげえわかりやすい・・・ <a href="https://t.co/hTxYPZJueY">pic.twitter.com/hTxYPZJueY</a></p>— (@terrierscript) <a href="https://twitter.com/terrierscript/status/1143809073227264000?ref_src=twsrc^tfw">2019年6月26日</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

Discussion