BackstopJSのScenariosを一括で設定するTips
はじめに
こんにちは kimizuy です。
本記事では BackstopJS の onBeforeScript を利用して backstop.json に個別に書いていた Scenarios の設定をまとめて書く方法をご紹介します。
例えば、一般的には以下のように scenarios に一つ一つ定義しますが、url や referenceUrl のドメイン部分は繰り返しになっています。また "delay": 3000 を scenarios すべてに追加したい場合はどうでしょうか。url ごとにカスタマイズする必要がないのなら一括で設定したいところですね。
  "scenarios": [
    {
      "label": "home",
      "url": "http://localhost:3000/",
      "referenceUrl": "https://example.com/"
    },
    {
      "label": "about",
      "url": "http://localhost:3000/about",
      "referenceUrl": "https://example.com/about"
    },
    {
      "label": "news",
      "url": "http://localhost:3000/news",
      "referenceUrl": "https://example.com/news"
    },
    {
      "label": "news/awesome-article",
      "url": "http://localhost:3000/news/awesome-article",
      "referenceUrl": "https://example.com/news/awesome-article"
    },
    // ...and more
  ],tldr
まず backstop.json には label だけ定義します。label には任意の文字列を与えられますが、今回は実際の URL のパス部分と揃えてください。
  "scenarios": [
    {
      "label": "home",
    },
    {
      "label": "about",
    },
    {
      "label": "news",
    },
    {
      "label": "news/awesome-article",
    },
    // ...and more
  ],以下は onBeforeScript で実行するスクリプトです。label を URL のパス部分として利用し、シナリオの共通部分をまとめて処理します。ホームページのパスだけは /home ではなく / なので if 文で出し分けています。
module.exports = async (page, scenario, viewport, isReference, browserContext) => {
  await require('./loadCookies')(browserContext, scenario) // ← デフォルト
  // 追加
  if (scenario.label === 'home') {
    scenario.url = `http://localhost:3000/`
    scenario.referenceUrl = `https://example.com/`
  } else {
    scenario.url = `http://localhost:3000/${scenario.label}`
    scenario.referenceUrl = `https://example.com/${scenario.label}`
  }
  scenario.delay = 1000
  scenario.misMatchThreshold = 0.3
}これで重複して定義することなく delay や misMatchThreshold の設定を一括で変更できます。
補足として上記は "onBeforeScript": "playwright/onBefore.js" の場合です。backstop init したときのデフォルトを利用しています。
ちなみに Senario は以下のリンクの順番で処理されるようです。
Backstopjs – Advanced Scenarios
参考
関連記事
弊社ブログには他にも BackstopJS の記事があります。
おわりに
onBeforeScript を利用して Scenarios をまとめて設定する方法をご紹介しました。省力化しつつすっきり書けて嬉しいですね!
以上、お読みいただきありがとうございました。
Gaji-Laboでは、React経験が豊富なフロントエンドエンジニアを募集しています
弊社ではReactの知見で事業作りに貢献したいフロントエンドエンジニアを募集しています。大きな制作会社や事業会社とはひと味もふた味も違うGaji-Laboを味わいに来ませんか?
もちろん、一緒にお仕事をしてくださるパートナーさんも随時募集中です。まずはお気軽に声をかけてください。お仕事お問い合わせや採用への応募、共に大歓迎です!
求人応募してみる!







