Javascript - Jest-puppeteer with typescript configuration
Table of Contents
About
How to install and configure puppeteer with Jest and Typescript.
You can also hook up puppeteer via the setup and tear down method. See custom-example-without-jest-puppeteer-preset
Articles Related
Prerequisites
You should have the configuration explained on this page: Jest and Typescript installation / configuration.
Steps
Install puppeteer and jest-puppeteer
- Install the library
yarn add jest-puppeteer puppeteer --dev
Install the Types
- install the puppeteer type file
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
{
"compilerOptions": {
.....
"types": [
.......
"puppeteer",
"jest-environment-puppeteer",
"expect-puppeteer"
]
}
Config
jest.config.js
- Merge the ts-jest and jest-puppeteer
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
preset: './js/Preset.js'
- Uncomment testEnvironment
// testEnvironment: "node"
jest-puppeteer
This configuration is not mandatory but will make a debugger keyword in the javascript code stop the execution by:
- starting puppeteer not in headless mode
- opening the devtool
let jest_puppeteer_conf = {
launch: {
timeout: 30000,
dumpio: true // Whether to pipe the browser process stdout and stderr
}
}
const isDebugMode = typeof v8debug === 'object' || /--debug|--inspect/.test(process.execArgv.join(' '));
if (isDebugMode) {
jest_puppeteer_conf.launch.headless = false; // for debug: to see what the browser is displaying
jest_puppeteer_conf.launch.slowMo = 250; // slow down by 250ms for each step
jest_puppeteer_conf.launch.devtools = true; // This lets you debug code in the application code browser
jest_puppeteer_conf.launch.args = [ '--start-maximized' ]; // maximise the screen
}
module.exports = jest_puppeteer_conf;
Test the configuration
Puppeteer's page and browser classes are automatically be exposed.
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.
Support
debug
await jestPuppeteer.debug()
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.
page is not defined
Be sure to uncomment testEnvironment
// testEnvironment: "node"