メインコンテンツへスキップ
Version: Next

puppeteer を使用する

グローバルセットアップ/ティアダウンAsync テスト環境 APIを使うことで、Jest は puppeteer を簡単に使用できます。

note

page.$eval, page.$$eval または page.evaluate をテストで使用している場合、Jestのスコープ外でパスする関数が実行されているため、現時点ではPuppeteerを使用したテストがいつのカバレッジの生成はできません。 Check out issue #7962 on GitHub for a workaround.

jest-puppeteer プリセットを使用する

Jest Puppeteer は、Puppeteer を使ってテストを実行するために必要な、すべての設定を提供します。

  1. First, install jest-puppeteer
npm install --save-dev jest-puppeteer
  1. Specify preset in your Jest configuration:
{
"preset": "jest-puppeteer"
}
  1. グローバルセットアップで、puppeteer を起動して、websocket のエンドポイントを指定する
describe('Google', () => {
beforeAll(async () => {
await page.goto('https://google.com');
});

it('should be titled "Google"', async () => {
await expect(page.title()).resolves.toMatch('Google');
});
});

依存関係をロードする必要はありません。 Puppeteer の pagebrowser クラスは自動的に公開されます。

詳しくはドキュメントを参照してください。

jest-puppeteer プリセットなしのカスタム例

スクラッチでpuppeteerを操作することもできます。 基本的な考え方は次の通りです。

  1. グローバルセットアップで puppeteer の WebSocket エンドポイントを起動する
  2. それぞれのテスト環境から puppeteer に接続する
  3. グローバルティアダウンで、puppeteer を終了する

GlobalSetup スクリプトの例を以下に挙げます。

setup.js
const {mkdir, writeFile} = require('fs').promises;
const os = require('os');
const path = require('path');
const puppeteer = require('puppeteer');

const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');

module.exports = async function () {
const browser = await puppeteer.launch();
// store the browser instance so we can teardown it later
// this global is only available in the teardown but not in TestEnvironments
globalThis.__BROWSER_GLOBAL__ = browser;

// use the file system to expose the wsEndpoint for TestEnvironments
await mkdir(DIR, {recursive: true});
await writeFile(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint());
};

そして、puppeteer 用のカスタムテスト環境も作ります。

puppeteer_environment.js
const {readFile} = require('fs').promises;
const os = require('os');
const path = require('path');
const puppeteer = require('puppeteer');
const NodeEnvironment = require('jest-environment-node').TestEnvironment;

const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');

class PuppeteerEnvironment extends NodeEnvironment {
constructor(config) {
super(config);
}

async setup() {
await super.setup();
// get the wsEndpoint
const wsEndpoint = await readFile(path.join(DIR, 'wsEndpoint'), 'utf8');
if (!wsEndpoint) {
throw new Error('wsEndpoint not found');
}

// connect to puppeteer
this.global.__BROWSER_GLOBAL__ = await puppeteer.connect({
browserWSEndpoint: wsEndpoint,
});
}

async teardown() {
if (this.global.__BROWSER_GLOBAL__) {
this.global.__BROWSER_GLOBAL__.disconnect();
}
await super.teardown();
}

getVmContext() {
return super.getVmContext();
}
}

module.exports = PuppeteerEnvironment;

Finally, we can close the puppeteer instance and clean-up the file

teardown.js
const fs = require('fs').promises;
const os = require('os');
const path = require('path');

const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
module.exports = async function () {
// close the browser instance
await globalThis.__BROWSER_GLOBAL__.close();

// clean-up the wsEndpoint file
await fs.rm(DIR, {recursive: true, force: true});
};

すべての準備が終われば、次のようにテストが書けます。

test.js
const timeout = 5000;

describe(
'/ (Home Page)',
() => {
let page;
beforeAll(async () => {
page = await globalThis.__BROWSER_GLOBAL__.newPage();
await page.goto('https://google.com');
}, timeout);

it('should load without error', async () => {
const text = await page.evaluate(() => document.body.textContent);
expect(text).toContain('google');
});
},
timeout,
);

最後に、これらのファイルを読み込むように jest.config.js を設定します。 ( jest-puppeteer プリセットは、水面下でこのようなことを行ってます)

module.exports = {
globalSetup: './setup.js',
globalTeardown: './teardown.js',
testEnvironment: './puppeteer_environment.js',
};

完全な動作例 はこちら。