puppeteer との連携
Global Setup/Teardown と Async Test Environment API を使用すると、Jest は puppeteer とスムーズに連携できます。
注記
Puppeteer を使用してテストファイルのコードカバレッジを生成することは、渡された関数が Jest のスコープ外で実行されるため、テストで page.$eval
、page.$$eval
、または page.evaluate
を使用している場合は、現在不可能です。回避策については、GitHub の issue #7962 を確認してください。
jest-puppeteer プリセットを使用する
Jest Puppeteer は、Puppeteer を使用してテストを実行するために必要なすべての構成を提供します。
- まず、
jest-puppeteer
をインストールします
- npm
- Yarn
- pnpm
npm install --save-dev jest-puppeteer
yarn add --dev jest-puppeteer
pnpm add --save-dev jest-puppeteer
- Jest 構成でプリセットを指定します
{
"preset": "jest-puppeteer"
}
- テストを記述します
describe('Google', () => {
beforeAll(async () => {
await page.goto('https://google.com');
});
it('should be titled "Google"', async () => {
await expect(page.title()).resolves.toMatch('Google');
});
});
依存関係を読み込む必要はありません。Puppeteer の page
および browser
クラスは自動的に公開されます
ドキュメントを参照してください。
jest-puppeteer プリセットを使用しないカスタム例
最初から puppeteer をフックすることもできます。基本的な考え方は次のとおりです。
- Global Setup で puppeteer の websocket エンドポイントを起動してファイルに書き込む
- 各 Test Environment から puppeteer に接続する
- Global Teardown で 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 用のカスタム Test Environment が必要です
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;
最後に、puppeteer インスタンスを閉じてファイルをクリーンアップできます
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',
};
完全な動作例のコードはこちらです。