Skip to content

Create a puppeteer plugin #28023

Closed
Closed
@chrisbreiding

Description

@chrisbreiding

What would you like?

Create a plugin that makes it easy to interact with the Cypress browser using Puppeteer. The plugin will require separate installation.

Message handlers are defined inside the Cypress config for utilizing Puppeteer like so:

// cypress.config.ts
import { setup, retry } from '@cypress/puppeteer'
import { defineConfig } from 'cypress'
import type { Browser as PuppeteerBrowser, Page } from 'puppeteer-core'

export default defineConfig({
  e2e: {
    setupNodeEvents (on) {
      setup({
        on,
        onMessage: {
		  // 'testNewTab' can be any string and there can be as many uniquely-named message handlers as needed
          async testNewTab (browser: PuppeteerBrowser) {
            const page = await retry<Promise<Page>>(async () => {
              const pages = await browser.pages()
              const page = pages.find((page) => page.url().includes('new-tab.html'))

              if (!page) throw new Error('Could not find page in usage')

              return page
            })

            const paragraph = await page.waitForSelector('p')
            const paragraphText = await page.evaluate((el) => el!.textContent, paragraph)
            const button = await page.waitForSelector('#send')
            const buttonText = await page.evaluate((el) => el!.textContent, button)

            button!.dispose()
            paragraph!.dispose()

            await page.close()

            return { paragraphText, buttonText }
          },
        },
      })
    },
  },
})

Note that a generic retry function is provided as well.

The message handler is invoked in the spec by specifying the message via the custom cy.puppeteer() command:

// spec.cy.ts
it('tests a second tab', () => {
    cy.visit('/cypress/fixtures/index.html')
    cy.get('button').click() // opens a new tab

    // this invokes the testNewTab message handler
    cy.puppeteer('testNewTab')
    .should('deep.equal', {
      paragraphText: 'This is the new tab',
      buttonText: 'Send message',
    })
})

The Cypress app itself should be updated to expect extra tabs and/or windows (any tabs/windows outside the main Cypress tab) being opened.

Why is this needed?

No response

Other

No response

Metadata

Metadata

Assignees

Labels

type: featureNew feature that does not currently exist

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions