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
You should have the configuration explained on this page: Jest and Typescript installation / configuration.
yarn add jest-puppeteer puppeteer --dev
yarn add @types/puppeteer --dev
yarn add @types/jest-environment-puppeteer --dev
yarn add @types/expect-puppeteer --dev
{
"compilerOptions": {
.....
"types": [
.......
"puppeteer",
"jest-environment-puppeteer",
"expect-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
)
preset: './js/Preset.js'
// testEnvironment: "node"
This configuration is not mandatory but will make a debugger keyword in the javascript code stop the execution by:
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;
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')
})
})
jest
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.
await jestPuppeteer.debug()
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.
Be sure to uncomment testEnvironment
// testEnvironment: "node"