跳至主要內容
版本:29.7

與 puppeteer 一起使用

使用 全域設定/清除非同步測試環境 API,Jest 可以順利與 puppeteer 搭配使用。

注意

如果您的測試使用 page.$evalpage.$$evalpage.evaluate,目前無法為使用 Puppeteer 的測試檔案產生程式碼涵蓋率,因為傳遞的函式是在 Jest 範圍之外執行的。請查看 GitHub 上的 議題 #7962,以取得解決方法。

使用 jest-puppeteer 預設值

Jest Puppeteer 提供所有必要的設定,讓您使用 Puppeteer 執行測試。

  1. 首先,安裝 jest-puppeteer
npm install --save-dev jest-puppeteer
  1. Jest 設定 中指定預設值
{
"preset": "jest-puppeteer"
}
  1. 撰寫測試
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

以下是「全域設定」腳本的範例

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;

最後,我們可以關閉 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',
};

以下是 完整範例 的程式碼。