Перейти к основной части
Version: 25.x

Использование Jest с Puppeteer

With the Global Setup/Teardown and Async Test Environment APIs, Jest can work smoothly with puppeteer.

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#

Jest Puppeteer предоставляет всю необходимую конфигурацию для запуска ваших тестов с помощью Puppeteer.

  1. Сначала установите jest-puppeteer
yarn add --dev jest-puppeteer
  1. Укажите preset в конфигурации 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 страницы и браузера

См. документацию.

Пользовательский пример без предустановленного jest-puppeteer#

You can also hook up puppeteer from scratch. Главная идея заключается в следующем:

  1. launch & file the websocket endpoint of puppeteer with Global Setup
  2. connect to puppeteer from each Test Environment
  3. close puppeteer with Global Teardown

Вот пример скрипта GlobalSetup

// setup.js
const {writeFile} = require('fs').promises;
const os = require('os');
const path = require('path');
const mkdirp = require('mkdirp');
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
global.__BROWSER_GLOBAL__ = browser;
// use the file system to expose the wsEndpoint for TestEnvironments
mkdirp.sync(DIR);
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');
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__ = await puppeteer.connect({
browserWSEndpoint: wsEndpoint,
});
}
async teardown() {
await super.teardown();
}
runScript(script) {
return super.runScript(script);
}
}
module.exports = PuppeteerEnvironment;

Наконец, мы можем закрыть экземпляр слушателя и очистить файл

// teardown.js
const os = require('os');
const path = require('path');
const rimraf = require('rimraf');
const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
module.exports = async function () {
// close the browser instance
await global.__BROWSER_GLOBAL__.close();
// clean-up the wsEndpoint file
rimraf.sync(DIR);
};

С учетом всех настроенных вещей мы теперь можем написать наши тесты как в примере:

// test.js
const timeout = 5000;
describe(
'/ (Home Page)',
() => {
let page;
beforeAll(async () => {
page = await global.__BROWSER__.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,
);

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',
};

Вот код [полного рабочего примера](https://github. com/xfumihiro/jest-puppeteer-example).