All Projects → smooth-code → Jest Puppeteer

smooth-code / Jest Puppeteer

Licence: mit
Run your tests using Jest & Puppeteer 🎪✨

Programming Languages

javascript
184084 projects - #8 most used programming language
HTML
75241 projects
shell
77523 projects

Projects that are alternatives of or similar to Jest Puppeteer

Frisby
Frisby is a REST API testing framework built on Jest that makes testing API endpoints easy, fast, and fun.
Stars: ✭ 1,484 (-54.58%)
Mutual labels:  jest, integration-testing
pythonista-chromeless
Serverless selenium which dynamically execute any given code.
Stars: ✭ 31 (-99.05%)
Mutual labels:  integration-testing, chromeless
Javascript Testing Best Practices
📗🌐 🚢 Comprehensive and exhaustive JavaScript & Node.js testing best practices (August 2021)
Stars: ✭ 13,976 (+327.79%)
Mutual labels:  jest, integration-testing
Mostly
They mostly come at night; mostly.
Stars: ✭ 78 (-97.61%)
Mutual labels:  jest, puppeteer
match-screenshot
A simple Jest or Chai matcher to compare screenshots, using Applitools Eyes
Stars: ✭ 14 (-99.57%)
Mutual labels:  jest, puppeteer
Dockest
Docker + Jest integration testing for Node.js
Stars: ✭ 81 (-97.52%)
Mutual labels:  jest, integration-testing
Puppeteer Examples
Puppeteer example scripts for running Headless Chrome from Node.
Stars: ✭ 2,781 (-14.88%)
Mutual labels:  jest, puppeteer
Differencify
Differencify is a library for visual regression testing
Stars: ✭ 572 (-82.49%)
Mutual labels:  jest, puppeteer
energy-use-case-trading-client
Energy Use Case Web UI for Lition Trading Platform
Stars: ✭ 23 (-99.3%)
Mutual labels:  jest, puppeteer
xstate-marionettist
Model based testing with Jest, XState and Puppeteer or Playwright made easy
Stars: ✭ 23 (-99.3%)
Mutual labels:  jest, puppeteer
Nuxt Jest Puppeteer
🚀 Nuxt.js zero configuration tests, run with Jest and Puppetter
Stars: ✭ 57 (-98.26%)
Mutual labels:  jest, puppeteer
puppeteer-screenshot-tester
Small library that allows us to compare screenshots generated by puppeteer in our tests.
Stars: ✭ 50 (-98.47%)
Mutual labels:  jest, puppeteer
Marvelheroes
Marvel Heroes
Stars: ✭ 54 (-98.35%)
Mutual labels:  jest, puppeteer
Gest
👨‍💻 A sensible GraphQL testing tool - test your GraphQL schema locally and in the cloud
Stars: ✭ 109 (-96.66%)
Mutual labels:  jest, integration-testing
Jest To Match Shape Of
A Jest matcher to verify the shape of an object. Makes integration testing simple.
Stars: ✭ 34 (-98.96%)
Mutual labels:  jest, integration-testing
Root Cause
🔍 Root Cause is a tool for troubleshooting Puppeteer and Playwright tests. 🔎
Stars: ✭ 205 (-93.73%)
Mutual labels:  jest, puppeteer
Cuprite
Headless Chrome/Chromium driver for Capybara
Stars: ✭ 743 (-77.26%)
Mutual labels:  integration-testing, chrome
Chromeless
🖥 Chrome automation made simple. Runs locally or headless on AWS Lambda.
Stars: ✭ 13,254 (+305.69%)
Mutual labels:  integration-testing, chrome
jest-puppeteer-istanbul
Collect code coverage information from end-to-end jest puppeteer tests
Stars: ✭ 26 (-99.2%)
Mutual labels:  integration-testing, puppeteer
awesome-javascript-testing
🔧 Awesome JavaScript testing resources
Stars: ✭ 28 (-99.14%)
Mutual labels:  jest, integration-testing

jest-puppeteer

Run your tests using Jest & Puppeteer 🎪

License Donate npm package npm downloads Build Status Code style Dependencies DevDependencies

# for jest 22~23
npm install --save-dev [email protected] puppeteer jest
# for jest 24+
npm install --save-dev jest-puppeteer puppeteer jest

Requires Jest v22+

# TypeScript users should install following type packages
npm install --save-dev @types/puppeteer @types/jest-environment-puppeteer @types/expect-puppeteer

Supporting jest-puppeteer

jest-puppeteer is an MIT-licensed open source project. It's an independent project with ongoing development made possible thanks to the support of these awesome backers. If you'd like to join them, please consider:

Gold Sponsors

Gold Sponsors are those who have pledged $100/month and more to jest-puppeteer.

gold-sponsors

Usage

Update your Jest configuration:

{
  "preset": "jest-puppeteer"
}

NOTE: Be sure to remove any existing testEnvironment option from your Jest configuration. The jest-puppeteer preset needs to manage that option itself.

Use Puppeteer in your tests:

import 'expect-puppeteer'

describe('Google', () => {
  beforeAll(async () => {
    await page.goto('https://google.com')
  })

  it('should display "google" text on page', async () => {
    await expect(page).toMatch('google')
  })
})

If you are using react-scripts, you will need to pass the environment via command line:

  "test": "react-scripts test --env=puppeteer",

or alternatively include the following comment at the top of each test file:

/**
 * @jest-environment puppeteer
 */

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:

jest --runInBand

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

jest --maxWorkers=2

Recipes

Writing tests using Puppeteer

Writing integration test can be done using Puppeteer API 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

// Assert that current page contains 'Text in the page'
await expect(page).toMatch('Text in the page')

Click a button

// Assert that a button containing text "Home" will be clicked
await expect(page).toClick('button', { text: 'Home' })

Fill a form

// Assert that a form will be filled
await expect(page).toFillForm('form[name="myForm"]', {
  firstName: 'James',
  lastName: 'Bond',
})

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.

await jestPuppeteer.debug()

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.

// jest-puppeteer.config.js
module.exports = {
  server: {
    command: 'node server.js',
    port: 4444,
  },
}

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 in jest-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. incognito is available if you want more isolation between running instances. More information available in jest-puppeteer-environment readme

// jest-puppeteer.config.js
module.exports = {
  launch: {
    dumpio: true,
    headless: process.env.HEADLESS !== 'false',
    product: 'chrome',
  },
  browserContext: 'default',
}

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:

// .eslintrc.js
module.exports = {
  env: {
    jest: true,
  },
  globals: {
    page: true,
    browser: true,
    context: true,
    jestPuppeteer: true,
  },
}

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.

// setup.js
require('expect-puppeteer')

// Your custom setup
// ...
// jest.config.js
module.exports = {
  // ...
  setupTestFrameworkScriptFile: './setup.js',
  // or
  setupFilesAfterEnv: ['./setup.js'],
}

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

module.exports = {
  projects: [
    {
      displayName: 'integration',
      preset: 'jest-puppeteer',
      transform: {
        '\\.tsx?$': 'babel-jest',
        '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
          'jest-transform-stub',
      },
      moduleNameMapper: {
        '^.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
          'jest-transform-stub',
      },
      modulePathIgnorePatterns: ['.next'],
      testMatch: [
        '<rootDir>/src/**/__integration__/**/*.test.ts',
        '<rootDir>/src/**/__integration__/**/*.test.tsx',
      ],
    },
    {
      displayName: 'unit',
      transform: {
        '\\.tsx?$': 'babel-jest',
        '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
          'jest-transform-stub',
      },
      moduleNameMapper: {
        '^.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
          'jest-transform-stub',
      },
      globalSetup: '<rootDir>/setupEnv.ts',
      setupFilesAfterEnv: ['<rootDir>/setupTests.ts'],
      modulePathIgnorePatterns: ['.next'],
      testMatch: [
        '<rootDir>/src/**/__tests_/**/*.test.ts',
        '<rootDir>/src/**/__tests__/**/*.test.tsx',
      ],
    },
  ],
}

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.

// custom-environment.js
const PuppeteerEnvironment = require('jest-environment-puppeteer')

class CustomEnvironment extends PuppeteerEnvironment {
  async setup() {
    await super.setup()
    // Your setup
  }

  async teardown() {
    // Your teardown
    await super.teardown()
  }
}

module.exports = CustomEnvironment

Then, assigning your js file path to the testEnvironment property in your Jest configuration.

{
  // ...
  "testEnvironment": "./custom-environment.js"
}

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 and globalTeardown.

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:

// global-setup.js
const { setup: setupPuppeteer } = require('jest-environment-puppeteer')

module.exports = async function globalSetup(globalConfig) {
  await setupPuppeteer(globalConfig)
  // Your global setup
}
// global-teardown.js
const { teardown: teardownPuppeteer } = require('jest-environment-puppeteer')

module.exports = async function globalTeardown(globalConfig) {
  // Your global teardown
  await teardownPuppeteer(globalConfig)
}

Then assigning your js file paths to the globalSetup and globalTeardown property in your Jest configuration.

{
  // ...
  "globalSetup": "./global-setup.js",
  "globalTeardown": "./global-teardown.js"
}

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

Create React App

You can find an example of create-react-app setup in this repository.

API

global.browser

Give access to the Puppeteer Browser.

it('should open a new page', async () => {
  const page = await browser.newPage()
  await page.goto('https://google.com')
})

global.page

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

it('should fill an input', async () => {
  await page.type('#myinput', 'Hello')
})

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 the browserContext option in your jest-puppeteer.config.js.

global.expect(page)

Helper to make Puppeteer assertions, see documentation.

await expect(page).toMatch('A text in the page')
// ...

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
it('should put test in debug mode', async () => {
  await jestPuppeteer.debug()
})

global.jestPuppeteer.resetPage()

Reset global.page

beforeEach(async () => {
  await jestPuppeteer.resetPage()
})

global.jestPuppeteer.resetBrowser()

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

beforeEach(async () => {
  await jestPuppeteer.resetBrowser()
})

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 can be specified in config. Since it is JavaScript, you can use all stuff you need, including environment.
  • connect <[object]> All Puppeteer connect options 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
  • browserPerWorker <[Boolean]> Allows to run tests for each jest worker in an individual browser.

Example 1

// jest-puppeteer.config.js
module.exports = {
  launch: {
    dumpio: true,
    headless: process.env.HEADLESS !== 'false',
  },
  server: {
    command: 'node server.js',
    port: 4444,
  },
}

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.

// jest-puppeteer.config.js
const wsEndpoint = fs.readFileSync(endpointPath, 'utf8')

module.exports = {
  connect: {
    browserWSEndpoint: wsEndpoint,
  },
  server: {
    command: 'node server.js',
    port: 4444,
  },
}

Inspiration

Thanks to Fumihiro Xue for his great Jest example.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].