Utilisation avec 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.
Utilisez le preset jest-puppeteer
Jest Puppeteer provides all required configuration to run your tests using Puppeteer.
- First, install
jest-puppeteer
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev jest-puppeteer
yarn add --dev jest-puppeteer
pnpm add --save-dev jest-puppeteer
bun add --dev jest-puppeteer
- Specify preset in your Jest configuration:
{
"preset": "jest-puppeteer"
}
- Écrivez votre test
describe('Google', () => {
beforeAll(async () => {
await page.goto('https://google.com');
});
it('should be titled "Google"', async () => {
await expect(page.title()).resolves.toMatch('Google');
});
});
Il n'y a pas besoin de charger des dépendances. Puppeteer's page and browser classes will automatically be exposed
See documentation.
Exemple personnalisé sans preset jest-puppeteer
Vous pouvez également brancher votre puppeteer à partir de zéro. L'idée de base est :
- launch & file the websocket endpoint of puppeteer with Global Setup
- se connecter à puppeteer depuis chaque environnement de test
- fermer puppeteer avec Global Teardown
Voici un exemple du script GlobalSetup
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();
// stocke l'instance du navigateur pour pouvoir la démonter plus tard
// ce global n'est disponible que lors du démontage, mais pas dans TestEnvironments.
globalThis.__BROWSER_GLOBAL__ = browser;
// utilise le système de fichiers pour exposer le wsEndpoint pour TestEnvironments
await mkdir(DIR, {recursive: true});
await writeFile(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint());
};
Ensuite, nous avons besoin d'un environnement de test personnalisé pour 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;
Enfin, nous pouvons fermer l'instance puppeteer et nettoyer le fichier
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 () {
// ferme l'instance du navigateur
await globalThis.__BROWSER_GLOBAL__.close();
// nettoie le fichier wsEndpoint
await fs.rm(DIR, {recursive: true, force: true});
};
Avec toutes les choses mises en place, nous pouvons maintenant écrire nos tests comme ceci :
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,
);
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.