What is jest-puppeteer?
jest-puppeteer is a Jest preset that allows you to use Puppeteer, a headless Chrome Node API, for end-to-end testing. It simplifies the setup and configuration needed to use Puppeteer with Jest, enabling you to write tests that interact with web pages in a browser-like environment.
What are jest-puppeteer's main functionalities?
Setup and Teardown
jest-puppeteer provides a simple way to configure global setup and teardown scripts, as well as a custom test environment for running Puppeteer tests.
module.exports = {
globalSetup: './setup.js',
globalTeardown: './teardown.js',
testEnvironment: './puppeteer_environment.js'
};
Writing Tests
You can write tests using Jest's syntax, and use Puppeteer's API to interact with the web page. In this example, the test navigates to Google's homepage and checks if the text 'google' is present.
describe('Google', () => {
beforeAll(async () => {
await page.goto('https://google.com');
});
it('should display "google" text on page', async () => {
await expect(page).toMatch('google');
});
});
Custom Matchers
jest-puppeteer allows you to extend Jest with custom matchers that can be used to assert conditions specific to Puppeteer. This example shows how to create a custom matcher to check if an element's text includes a specific string.
expect.extend({
async toMatchText(received, argument) {
const text = await received.evaluate(el => el.textContent);
if (text.includes(argument)) {
return {
message: () => `expected ${text} to include ${argument}`,
pass: true
};
} else {
return {
message: () => `expected ${text} to include ${argument}`,
pass: false
};
}
}
});
Other packages similar to jest-puppeteer
puppeteer
Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. While jest-puppeteer is a preset that integrates Puppeteer with Jest, Puppeteer itself is more low-level and requires more setup to use with a testing framework.
cypress
Cypress is an end-to-end testing framework that provides a rich, interactive environment for writing and running tests. Unlike jest-puppeteer, which uses Puppeteer to control a headless browser, Cypress runs in the browser and provides a more integrated and user-friendly experience.
testcafe
TestCafe is a Node.js tool to automate end-to-end web testing. It does not require browser plugins and works with all modern browsers. Compared to jest-puppeteer, TestCafe provides a more streamlined API and built-in support for parallel test execution.
jest-puppeteer
Jest preset containing all required configuration for writing integration tests using Puppeteer.
npm install jest-puppeteer puppeteer
Usage
module.exports = {
preset: "jest-puppeteer",
};