Headless Testing with Playwright and Jest | Hacker Noon

Author profile picture

Playwright is a NodeJS package which can be used to automate Chrome, Firefox, Edge and Safari browsers in a headless manner.

It is developed by the team that created Puppeteer at Google and is actively developed at Microsoft.

The advantage of using Headless Testing is that it uses a real browser, but is much faster to run your tests than for example Selenium.

The combination of Jest, a NodeJS test runner framework maintained by Facebook with Playwright makes for an excellent Headless Testing combination.

Installing jest-playwright

There’s a

jest-playwright

NPM library which makes it easy to get started with Jest and Playwright.

The package comes in combination with a

jest-playwright-preset

which you can use as a preset for Jest in

jest.config.js

.

Installing these packages is easy:

npm install -D jest jest-playwright-preset playwright

Once you’ve included the Playwright preset, you can either run the tests on a browser on your computer, or connect it to an online browser grid.

module.exports = {
rootDir: '.',
testTimeout: 20000,
testMatch: [
'<rootDir>/*.spec.js'
],
preset: 'jest-playwright-preset'
}

Configuring jest-playwright

To connect your tests to a Headless Browser grid, please specify the connectBrowserApp setting in a file called

jest-playwright.config.js

.

module.exports = {
connectBrowserApp: {
wsEndpoint: 'wss://chrome.headlesstesting.com/?token=[YOUR-API-TOKEN]&browserVersion=dev'
}
}
This will instruct Jest Playwright to start and use a headless Chrome browser on the HeadlessTesting.com grid.

Running your first test with jest-playwright

Now you are ready to run your first test with Jest and Playwright.
To get started, create a new test file

sample.spec.js

:

describe('Google', () => {
beforeAll(async () => {
await page.goto('https://google.com')
})
it('should display google text on page', async () => {
await expect(page).toMatch('google')
})
})
You can now run this sample test:

$ jest

Depending on whether you want to run this test locally or on a cloud platform, the test will start a headless browser, navigate to Google and verify if the word google appears on the page.

expect-playwright

There’s a NPM package available called

expect-playwright

. This package provides several Jest utility matchers for Playwright. The package makes it easier and cleaner to write assertions in your test scripts.

To get started, you can install the library:

npm install -D expect-playwright
Now you can use various matchers, for example:

await expect(page).toHaveText("h1", "MyPage")

Conclusion

Jest together with Playwright is a great combination to do Headless Testing. Both frameworks are under active development and keep getting better.

Comments

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!

read original article here