Using with puppeteer
With the Global Setup/Teardown and Async Test Environment APIs, Jest can work smoothly with puppeteer.
nota
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.
Use jest-puppeteer Preset
Jest Puppeteer provides all required configuration to run your tests using 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
- 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');
});
});
There's no need to load any dependencies. Puppeteer's page
and browser
classes will automatically be exposed
See documentation.
Custom example without jest-puppeteer preset
You can also hook up puppeteer from scratch. 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());
};