0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PlaywrightでChrome拡張機能のテストをする時にやること

Posted at

Playwrihtでは以下のようにChrome拡張機能のテストを行うことができます。

const { chromium } = require('playwright');

(async () => {
  const pathToExtension = require('path').join(__dirname, 'my-extension');
  const userDataDir = '/tmp/test-user-data-dir';
  const browserContext = await chromium.launchPersistentContext(userDataDir, {
    channel: 'chromium',
    args: [
      `--disable-extensions-except=${pathToExtension}`,
      `--load-extension=${pathToExtension}`
    ]
  });
  let [backgroundPage] = browserContext.backgroundPages();
  if (!backgroundPage)
    backgroundPage = await browserContext.waitForEvent('backgroundpage');

  // ここにやりたいことを書く

  await browserContext.close();
})();

ですがChrome ウェブストアにてリリースされた拡張機能をテストするにはこれとは少し違います。
2つの手段があると思います。

方法1:crxファイルを入手しフォルダーに解凍し、前述のテストをする

Chrome拡張機能に使われているcrxファイルは中身はただのzipファイルです。
どうにかして入手できれば解凍し配置することで前述のテストができます。

この記事にはダウンロードできるみたいな話ですが、実際は空のレスポンスが返ってくるだけでした。(誰か知っていたら教えてください)

curl -LO https://clients2.google.com/service/update2/crx?response=redirect&prodversion=[PRODVERSION]&acceptformat=crx2,crx3&x=id%3D[EXTENSIONID]%26uc

方法2:chrome拡張機能をインストールしたユーザーデータを作成し、そのユーザーデータを使ってテストをする

普段はPlaywrightのcodegenを使い、テストコードの生成を行っております。
そこにひと工夫入れることで、ユーザーデータの作成と、テストコードの実行を同時にすることができました。
具体的には以下のコードです。

const { chromium } = require('@playwright/test');

(async () => {
  const browser = await chromium.launch({
    headless: false,
    ignoreDefaultArgs: ['--disable-extensions'],
  });

  const userDataDir = './data';
  const context = await chromium.launchPersistentContext(userDataDir, {
    headless: false,
    channel: 'chromium',
  });

  await context.route('**/*', route => route.continue());

  const page = await context.newPage();
  await page.goto('https://chromewebstore.google.com/');

  // ここでChrome拡張機能のインストールをする
  await page.pause();
  // インストールができたらレコードボタンを押してコード生成
})();

デフォルトではPlaywrightはChromeに--disable-extensionsを渡すので、Chrome拡張をインストールできません。ignoreDefaultArgsに渡すことで拡張機能無効化を無効化します。

参考:
https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/chromium/chromiumSwitches.ts#L70

後はユーザーデータを使用していつもの如くテストを実行するだけです。

  const userDataDir = './data';
  const context = await chromium.launchPersistentContext(userDataDir,{
  ...

まとめ

Chrome拡張機能に関する記事はなかなかありませんが、Playwrightはそういったところまでカバーできます。
今後も使い続けたいですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?