Javascript - Jest-puppeteer with typescript configuration

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript)

1 - About

How to install and configure puppeteer with Jest and Typescript.

3 - Prerequisites

You should have the configuration explained on this page: Jest and Typescript installation / configuration.

4 - Steps

4.1 - Install puppeteer and jest-puppeteer

  • Install the library
yarn add jest-puppeteer puppeteer --dev
Advertising

4.2 - Install the Types

yarn add @types/puppeteer --dev
yarn add @types/jest-environment-puppeteer --dev
yarn add @types/expect-puppeteer --dev
  • Add them also in the compile path
tsconfig.json
{
  "compilerOptions": {
   .....
    "types": [
     .......
      "puppeteer",
      "jest-environment-puppeteer",
      "expect-puppeteer"
    ]
  }

4.3 - Preset config of jest.config.js

  • Merge the ts-jest and jest-puppeteer
./js/Preset.js
const ts_preset = require('ts-jest/jest-preset')
const puppeteer_preset = require('jest-puppeteer/jest-preset')
 
 
module.exports = Object.assign(
    ts_preset, 
    puppeteer_preset
)
  • Change the config
jest.config.js
preset: './js/Preset.js'

4.4 - Test the configuration

Puppeteer's page and browser classes are automatically be exposed.

Puppeteer.test.ts
describe('Google', () => {
 
    beforeAll(async () => {
        await page.goto('https://google.com')
    })
 
    it('should display "google" text on page', async () => {
        await expect(page).toMatch('google')
    })
 
})
  • Run
jest
  • Result
 PASS  js/__tests__/Google.test.ts (5.688s)
  Google
    √ should display "google" text on page (9ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.807s
Ran all test suites.
Advertising

4.5 - Support

4.5.1 - debug

await jestPuppeteer.debug()

4.5.2 - error TS2304: Cannot find name 'page'.

TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    js/__tests__/Google.test.ts:17:15 - error TS2304: Cannot find name 'page'.

    17         await page.goto('https://google.com')
                     ~~~~

be sure to add the types in your compile path of the tsconfig.json file.

5 - Documentation / Reference