jest-puppeteer

Run tests using Jest & Puppeteer

README

🎪 jest-puppeteer


npm version
npm dm
npm dt

Installation


Install packages


  1. ```bash
  2. npm install --save-dev jest-puppeteer puppeteer jest
  3. ```

Update your Jest configuration


  1. ```json
  2. {
  3.   "preset": "jest-puppeteer"
  4. }
  5. ```

Note

Be sure to remove any existing testEnvironment option from your Jest configuration.


Write tests


  1. ```js
  2. import "expect-puppeteer";

  3. describe("Google", () => {
  4.   beforeAll(async () => {
  5.     await page.goto("https://google.com");
  6.   });

  7.   it('should display "google" text on page', async () => {
  8.     await expect(page).toMatch("google");
  9.   });
  10. });
  11. ```

Running puppeteer in CI environments


Most continuous integration platforms limit the number of threads one can use. If you have more than one test suite running puppeteer chances are that your test will timeout. This is because jest will try to run puppeteer in parallel and the CI platform won't be able to handle all the parallel jobs in time. A fix to this is to run your test serially when in a CI environment. Users have discovered that running test serially in such environments can render up to 50% of performance gains.

This can be achieved through the CLI by running:

  1. ```sh
  2. jest --runInBand
  3. ```

Alternatively, you can set jest to use as a max number of workers the amount that your CI environment supports:

  1. ```
  2. jest --maxWorkers=2
  3. ```

Recipes


TypeScript


Install types:

  1. ```bash
  2. npm install --save-dev @types/puppeteer @types/jest-environment-puppeteer @types/expect-puppeteer
  3. ```

Writing tests using Puppeteer


Writing integration test can be done using [Puppeteer API](<(https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md)>) but it can be complicated and hard because API is not designed for testing.

To make it simpler, expect-puppeteer API add some specific matchers if you make expectation on a Puppeteer Page.

Some examples:

Find a text in the page


  1. ```js
  2. // Assert that current page contains 'Text in the page'
  3. await expect(page).toMatch("Text in the page");
  4. ```

Click a button


  1. ```js
  2. // Assert that a button containing text "Home" will be clicked
  3. await expect(page).toClick("button", { text: "Home" });
  4. ```

Fill a form


  1. ```js
  2. // Assert that a form will be filled
  3. await expect(page).toFillForm('form[name="myForm"]', {
  4.   firstName: "James",
  5.   lastName: "Bond",
  6. });
  7. ```

Put in debug mode


Debugging tests can be hard sometimes and it is very useful to be able to pause tests in order to inspect the browser. Jest Puppeteer exposes a method jestPuppeteer.debug() that suspends test execution and gives you opportunity to see what's going on in the browser.

  1. ```js
  2. await jestPuppeteer.debug();
  3. ```

Start a server


Jest Puppeteer integrates a functionality to start a server when running your test suite. It automatically closes the server when tests are done.

To use it, specify a server section in your jest-puppeteer.config.js.

  1. ```js
  2. // jest-puppeteer.config.js
  3. module.exports = {
  4.   server: {
  5.     command: "node server.js",
  6.     port: 4444,
  7.   },
  8. };
  9. ```

Other options are documented in jest-dev-server.

Configure Puppeteer


Jest Puppeteer automatically detects the best config to start Puppeteer but sometimes you may need to specify custom options. All Puppeteer launch or connect options can be specified injest-puppeteer.config.js at the root of the project. Since it is JavaScript, you can use all the stuff you need, including environment.

To run Puppeteer on Firefox, you can set the launch.product property to firefox. By default, the value is chrome which will use Puppeteer on Chromium.

The browser context can be also specified. By default, the browser context is shared (value of default). The incognito value is also available, in case you want more isolation between running instances. More information available in jest-puppeteer-environment readme

Default config values:

  1. ```js
  2. // jest-puppeteer.config.js
  3. module.exports = {
  4.   launch: {
  5.     dumpio: true,
  6.     headless: process.env.HEADLESS !== "false",
  7.     product: "chrome",
  8.   },
  9.   browserContext: "default",
  10. };
  11. ```

Configure ESLint


Jest Puppeteer exposes three new globals: browser, page, context. If you want to avoid errors, you can add them to your .eslintrc.js:

  1. ```js
  2. // .eslintrc.js
  3. module.exports = {
  4.   env: {
  5.     jest: true,
  6.   },
  7.   globals: {
  8.     page: true,
  9.     browser: true,
  10.     context: true,
  11.     jestPuppeteer: true,
  12.   },
  13. };
  14. ```

Custom setupTestFrameworkScriptFile or setupFilesAfterEnv


If you use custom setup files, you'll need to include expect-puppeteer yourself in order to use the matchers it provides. Add the following to your setup file.

  1. ```js
  2. // setup.js
  3. require("expect-puppeteer");

  4. // Your custom setup
  5. // ...
  6. ```

  1. ```js
  2. // jest.config.js
  3. module.exports = {
  4.   // ...
  5.   setupTestFrameworkScriptFile: "./setup.js",
  6.   // or
  7.   setupFilesAfterEnv: ["./setup.js"],
  8. };
  9. ```

You may want to consider using multiple projects in Jest since setting your own setupFilesAfterEnv and globalSetup can cause globals to be undefined.

  1. ```js
  2. module.exports = {
  3.   projects: [
  4.     {
  5.       displayName: "integration",
  6.       preset: "jest-puppeteer",
  7.       transform: {
  8.         "\\.tsx?$": "babel-jest",
  9.         ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$":
  10.           "jest-transform-stub",
  11.       },
  12.       moduleNameMapper: {
  13.         "^.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$":
  14.           "jest-transform-stub",
  15.       },
  16.       modulePathIgnorePatterns: [".next"],
  17.       testMatch: [
  18.         "<rootDir>/src/**/__integration__/**/*.test.ts",
  19.         "<rootDir>/src/**/__integration__/**/*.test.tsx",
  20.       ],
  21.     },
  22.     {
  23.       displayName: "unit",
  24.       transform: {
  25.         "\\.tsx?$": "babel-jest",
  26.         ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$":
  27.           "jest-transform-stub",
  28.       },
  29.       moduleNameMapper: {
  30.         "^.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$":
  31.           "jest-transform-stub",
  32.       },
  33.       globalSetup: "<rootDir>/setupEnv.ts",
  34.       setupFilesAfterEnv: ["<rootDir>/setupTests.ts"],
  35.       modulePathIgnorePatterns: [".next"],
  36.       testMatch: [
  37.         "<rootDir>/src/**/__tests_/**/*.test.ts",
  38.         "<rootDir>/src/**/__tests__/**/*.test.tsx",
  39.       ],
  40.     },
  41.   ],
  42. };
  43. ```

Extend PuppeteerEnvironment


Sometimes you want to use your own environment, to do that you can extend PuppeteerEnvironment.

First, create your own js file for custom environment.

  1. ```js
  2. // custom-environment.js
  3. const PuppeteerEnvironment = require("jest-environment-puppeteer");

  4. class CustomEnvironment extends PuppeteerEnvironment {
  5.   async setup() {
  6.     await super.setup();
  7.     // Your setup
  8.   }

  9.   async teardown() {
  10.     // Your teardown
  11.     await super.teardown();
  12.   }
  13. }

  14. module.exports = CustomEnvironment;
  15. ```

Then, assigning your js file path to the [testEnvironment](https://facebook.github.io/jest/docs/en/configuration.html#testenvironment-string) property in your Jest configuration.

  1. ```js
  2. {
  3.   // ...
  4.   "testEnvironment": "./custom-environment.js"
  5. }
  6. ```

Now your custom setup and teardown will be triggered before and after each test suites.

Create your own globalSetup and globalTeardown


It is possible to create your own [globalSetup](https://facebook.github.io/jest/docs/en/configuration.html#globalsetup-string) and [globalTeardown](https://facebook.github.io/jest/docs/en/configuration.html#globalteardown-string).

For this use case, jest-environment-puppeteer exposes two methods: setup and teardown, so that you can wrap them with your own global setup and global teardown methods as the following example:

  1. ```js
  2. // global-setup.js
  3. const { setup: setupPuppeteer } = require("jest-environment-puppeteer");

  4. module.exports = async function globalSetup(globalConfig) {
  5.   await setupPuppeteer(globalConfig);
  6.   // Your global setup
  7. };
  8. ```

  1. ```js
  2. // global-teardown.js
  3. const { teardown: teardownPuppeteer } = require("jest-environment-puppeteer");

  4. module.exports = async function globalTeardown(globalConfig) {
  5.   // Your global teardown
  6.   await teardownPuppeteer(globalConfig);
  7. };
  8. ```

Then assigning your js file paths to the [globalSetup](https://facebook.github.io/jest/docs/en/configuration.html#globalsetup-string) and [globalTeardown](https://facebook.github.io/jest/docs/en/configuration.html#globalteardown-string) property in your Jest configuration.

  1. ```js
  2. {
  3.   // ...
  4.   "globalSetup": "./global-setup.js",
  5.   "globalTeardown": "./global-teardown.js"
  6. }
  7. ```

Now your custom globalSetup and globalTeardown will be triggered once before and after all test suites.

Create React App



API


global.browser


Give access to the Puppeteer Browser.

  1. ```js
  2. it("should open a new page", async () => {
  3.   const page = await browser.newPage();
  4.   await page.goto("https://google.com");
  5. });
  6. ```

global.page


Give access to a Puppeteer Page opened at start (you will use it most of time).

  1. ```js
  2. it("should fill an input", async () => {
  3.   await page.type("#myinput", "Hello");
  4. });
  5. ```

global.context


Give access to a browser context that is instantiated when the browser is launched. You can control whether each test has its own isolated browser context using thebrowserContext option in your jest-puppeteer.config.js.

global.expect(page)


Helper to make Puppeteer assertions, see documentation.

  1. ```js
  2. await expect(page).toMatch("A text in the page");
  3. // ...
  4. ```

global.jestPuppeteer.debug()


Put test in debug mode.

- Jest is suspended (no timeout)
- A debugger instruction to Chromium, if Puppeteer has been launched with { devtools: true } it will stop

  1. ```js
  2. it("should put test in debug mode", async () => {
  3.   await jestPuppeteer.debug();
  4. });
  5. ```

global.jestPuppeteer.resetPage()


Reset global.page

  1. ```js
  2. beforeEach(async () => {
  3.   await jestPuppeteer.resetPage();
  4. });
  5. ```

global.jestPuppeteer.resetBrowser()


Reset global.browser, global.context, and global.page

  1. ```js
  2. beforeEach(async () => {
  3.   await jestPuppeteer.resetBrowser();
  4. });
  5. ```

jest-puppeteer.config.js


You can specify a jest-puppeteer.config.js at the root of the project or define a custom path using JEST_PUPPETEER_CONFIG environment variable.

- `launch` <[object]> [All Puppeteer launch options](https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.puppeteerlaunchoptions.md) can be specified in config. Since it is JavaScript, you can use all stuff you need, including environment.- `connect` <[object]> [All Puppeteer connect options](https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.connectoptions.md) can be specified in config. This is an alternative to `launch` config, allowing you to connect to an already running instance of Chrome.- `server` <[Object]> Server options allowed by [jest-dev-server](https://github.com/smooth-code/jest-puppeteer/tree/master/packages/jest-dev-server)- `browserPerWorker` <[Boolean]> Allows to run tests for each [jest worker](https://jestjs.io/docs/cli#--maxworkersnumstring) in an individual browser.- `exitOnPageError` <[boolean]> Exits page on any global error message thrown. Defaults to true.

Example 1


  1. ```js
  2. // jest-puppeteer.config.js
  3. module.exports = {
  4.   launch: {
  5.     dumpio: true,
  6.     headless: process.env.HEADLESS !== "false",
  7.   },
  8.   server: {
  9.     command: "node server.js",
  10.     port: 4444,
  11.   },
  12. };
  13. ```

Example 2


This example uses an already running instance of Chrome by passing the active web socket endpoint to connect. This is useful, for example, when you want to connect to Chrome running in the cloud.

  1. ```js
  2. // jest-puppeteer.config.js
  3. const wsEndpoint = fs.readFileSync(endpointPath, "utf8");

  4. module.exports = {
  5.   connect: {
  6.     browserWSEndpoint: wsEndpoint,
  7.   },
  8.   server: {
  9.     command: "node server.js",
  10.     port: 4444,
  11.   },
  12. };
  13. ```

Inspiration


Thanks to Fumihiro Xue for his great Jest example.

License


MIT