Categories
Automated Testing Playwright

TypeScript!

I recently changed jobs 🎉

One of the biggest things I noticed since changing jobs nearly 3 years ago was the prevalence of TypeScript: JavaScript With Syntax For Types. Most, if not all, of the jobs I were looking at were dev teams using TypeScript – driven by the increasing use full stack Node.js.

It’s only week 2 in my new job but I’ve already set up an e2e testing framework using Playwright and it’s all in TypeScript 😊 I thought I’d share the main differences and I’ve created a sample repository to do so!

To use TypeScript on a front-end codebase running in a browser you need to compile/transpile it into JavaScript (which a browser understands).

Fortunately Playwright doesn’t require this step as Playwright runs your TypeScript code directly.

The first thing to do is add typescript to your project and add a tsconfig.json file to your project.

I use Playwright Test – and the main difference between a TypeScript spec file (*.spec.ts) and a JavaScript one (*.spec.js) is the import statements:

import { test, expect } from '@playwright/test'
import { visitHomePage } from '../lib/actions/nav'

test('can wait for an element to appear', async ({ page }) => {
  await visitHomePage(page)
  await page.waitForSelector('#elementappearschild', { state: 'visible', timeout: 5000 })
})

test('can use an element that appears after on page load', async ({ page }) => {
  await visitHomePage(page)
  const text = await page.textContent('#loadedchild')
  expect(text).toBe('Loaded!')
})

whereas in JavaScript the first two lines were:

const nav = require('../lib/actions/nav')
const { test, expect } = require('@playwright/test')

The main differences are in the library code.

import { Page } from '@playwright/test'
import config from 'config'

export async function visitHomePage (page: Page) {
  return await page.goto(`${config.get('baseURL')}`)
}

export async function goToPath (page: Page, path: string) {
  return await page.goto(`${config.get('baseURL')}/${path}`)
}

You will see the types being added, fortunately Playwright provides type definitions which are imported here.

Previously, this same file looked like:

const config = require('config')

async function visitHomePage (page) {
  return await page.goto(`${config.get('baseURL')}`)
}

async function goToPath (page, path) {
  return await page.goto(`${config.get('baseURL')}/${path}`)
}

module.exports = {
  visitHomePage,
  goToPath
}

The other main thing to update is if you use classes you define types against all the properties.

Everything else is about the same.

My fully working TypeScript example of Playwright Test is here: https://github.com/alisterscott/playwright-test-ts-demo

Enjoy TypeScripting 😀

Leave a Reply

Your email address will not be published. Required fields are marked *