Test Runners

With a few lines of code, you can hook up Playwright to your favorite JavaScript test runner.

Jest / Jasmine

For Jest, jest-playwright can be used. However for a light-weight solution, requiring playwright directly works fine. Jest shares it’s syntax with Jasmine, so this applies to Jasmine as well.

  1. const {chromium} = require('playwright');
  2. const expect = require('expect');
  3. let browser;
  4. let page;
  5. beforeAll(async () => {
  6. browser = await chromium.launch();
  7. });
  8. afterAll(async () => {
  9. await browser.close();
  10. });
  11. beforeEach(async () => {
  12. page = await browser.newPage();
  13. });
  14. afterEach(async () => {
  15. await page.close();
  16. });
  17. it('should work', async () => {
  18. await page.goto('https://www.example.com/');
  19. expect(await page.title()).toBe('Example Domain');
  20. });

AVA

Tests run concurrently in AVA, so a single page variable cannot be shared between tests. Instead, create new pages with a macro function.

  1. const {chromium} = require('playwright');
  2. const test = require('ava').default;
  3. const browserPromise = chromium.launch();
  4. async function pageMacro(t, callback) {
  5. const browser = await browserPromise;
  6. const page = await browser.newPage();
  7. try {
  8. await callback(t, page);
  9. } finally {
  10. await page.close();
  11. }
  12. }
  13. test('should work', pageMacro, async (t, page) => {
  14. await page.goto('https://www.example.com/');
  15. t.is(await page.title(), 'Example Domain');
  16. });

Mocha

Mocha looks very similar to the Jest/Jasmine setup, and functions in the same way.

  1. const {chromium} = require('playwright');
  2. const assert = require('assert');
  3. let browser;
  4. before(async() => {
  5. browser = await chromium.launch();
  6. });
  7. after(async () => {
  8. await browser.close();
  9. });
  10. let page;
  11. beforeEach(async() => {
  12. page = await browser.newPage();
  13. });
  14. afterEach(async () => {
  15. await page.close();
  16. });
  17. it('should work', async () => {
  18. await page.goto('https://www.example.com/');
  19. assert.equal(await page.title(), 'Example Domain');
  20. });

IDE support

If using TypeScript, add types to your variables like:

  1. let page: import('playwright').Page;

If using JavaScript, you can still get nice autocompletions in VSCode or WebStorm by using JSDoc.

  1. /** @type {import('playwright').Page} */
  2. let page;

Multiple Browsers

These simple examples can be extended to support multiple browsers using an environment variable.

  1. const {chromium, webkit, firefox} = require('playwright');
  2. const browserName = process.env.BROWSER || 'webkit';
  3. let browser;
  4. beforeAll(async() => {
  5. browser = await {chromium, webkit, firefox}[browserName].launch();
  6. });

Then set BROWSER=firefox to run your tests with firefox, or any other browser.