与 puppeteer 一起使用
借助 全局设置/拆卸 和 异步测试环境 API,Jest 可以与 puppeteer 顺利工作。
¥With the Global Setup/Teardown and Async Test Environment APIs, Jest can work smoothly with puppeteer.
如果你的测试使用 page.$eval
、page.$$eval
或 page.evaluate
,则当前无法使用 Puppeteer 生成测试文件的代码覆盖率,因为传递的函数是在 Jest 范围之外执行的。查看 GitHub 上的 问题#7962 以获取解决方法。
¥Generating code coverage for test files using Puppeteer is currently not possible if your test uses page.$eval
, page.$$eval
or page.evaluate
as the passed function is executed outside of Jest's scope. Check out issue #7962 on GitHub for a workaround.
使用 jest-puppeteer 预设
¥Use jest-puppeteer Preset
Jest Puppeteer 提供了使用 Puppeteer 运行测试所需的所有配置。
¥Jest Puppeteer provides all required configuration to run your tests using Puppeteer.
-
首先,安装
jest-puppeteer
¥First, install
jest-puppeteer
- npm
- Yarn
- pnpm
npm install --save-dev jest-puppeteer
yarn add --dev jest-puppeteer
pnpm add --save-dev jest-puppeteer
-
在 Jest 配置 中指定预设:
¥Specify preset in your Jest configuration:
{
"preset": "jest-puppeteer"
}
-
写下你的测试
¥Write your test
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
类将自动暴露
¥There's no need to load any dependencies. Puppeteer's page
and browser
classes will automatically be exposed
参见 文档。
¥See documentation.
没有 jest-puppeteer 预设的自定义示例
¥Custom example without jest-puppeteer preset
你还可以从头开始连接木偶师。基本思想是:
¥You can also hook up puppeteer from scratch. The basic idea is to:
-
使用全局设置启动并归档 puppeteer 的 websocket 端点
¥launch & file the websocket endpoint of puppeteer with Global Setup
-
从每个测试环境连接到 puppeteer
¥connect to puppeteer from each Test Environment
-
通过 Global Teardown 关闭 puppeteer
¥close puppeteer with Global Teardown
这是 GlobalSetup 脚本的示例
¥Here's an example of the GlobalSetup script
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 定制的测试环境
¥Then we need a custom Test Environment for puppeteer
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 实例并清理文件
¥Finally, we can close the puppeteer instance and clean-up the file
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});
};
完成所有设置后,我们现在可以像这样编写测试:
¥With all the things set up, we can now write our tests like this:
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
预设在幕后执行类似的操作。)
¥Finally, set jest.config.js
to read from these files. (The jest-puppeteer
preset does something like this under the hood.)
module.exports = {
globalSetup: './setup.js',
globalTeardown: './teardown.js',
testEnvironment: './puppeteer_environment.js',
};
这是 完整的工作示例 的代码。
¥Here's the code of full working example.