与 puppeteer 一起使用
note
如果你的测试在 jest 范围之外通过传递, page.$$eval
or page.evaluate
函数来实现。目前无法通过 Puppeteer 生成正确的代码覆盖率。 可以通过查看github issue #7962 来解决该问题。
Jest Puppeteer provides all required configuration to run your tests using Puppeteer.
- First, install
jest-puppeteer
- npm
- Yarn
yarn add --dev jest-puppeteer
- Specify preset in your :
{
"preset": "jest-puppeteer"
}
- Write your test
There’s no need to load any dependencies. There’s no need to load any dependencies. Puppeteer’s page
and browser
classes will automatically be exposed
Custom example without jest-puppeteer preset
You can also hook up puppeteer from scratch. The basic idea is to: The basic idea is to:
- launch & file the websocket endpoint of puppeteer with Global Setup
- connect to puppeteer from each Test Environment
- close puppeteer with Global Teardown
Here’s an example of the GlobalSetup script
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());
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 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() {
}
}
module.exports = PuppeteerEnvironment;
Finally, we can close the puppeteer instance and clean-up the file
teardown.js
With all the things set up, we can now write our tests like this:
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,
);
module.exports = {
globalSetup: './setup.js',
globalTeardown: './teardown.js',
};
Here’s the code of .