Exit course
Chapter 6 of 11 Intermediate 6 min read 2 quick checks Updated

Page Objects in WebdriverIO

Watch this chapter Starts at 3:45 in the 9:06 course video.
On this page
  1. The base page
  2. Selectors as getters
  3. Actions return nothing, specs assert
  4. The spec
  5. Run it

After four chapters the specs repeat themselves: #username, #password and the Login button appear in more than one file, and the day the login form changes you edit every one of them. A page object puts the selectors and actions for one page in one class, so specs read like a description of what the user does. The npm init wdio starter already generated page objects; this chapter improves them and explains the WebdriverIO-specific details.

The general pattern, and when page objects stop paying off, is covered in the Page Object Model course. Here we focus on how to write them well in WebdriverIO.

The base page#

test/pageobjects/page.ts holds what every page shares:

import { $, browser } from '@wdio/globals'

export default class Page {
    public get flash () {
        return $('#flash')
    }

    public open (path: string) {
        return browser.url(`/${path}`)
    }
}

The starter's version hard-coded https://the-internet.herokuapp.com/ in open(). Using a relative path lets baseUrl from the config decide where the app lives, so the same page objects work against localhost, staging and production. The flash message appears on both the login and the secure page, so it belongs here.

Selectors as getters#

test/pageobjects/login.page.ts:

import { $ } from '@wdio/globals'
import Page from './page.js'

class LoginPage extends Page {
    public get inputUsername () {
        return $('#username')
    }

    public get inputPassword () {
        return $('#password')
    }

    public get btnSubmit () {
        return $('button*=Login')
    }

    public async login (username: string, password: string) {
        await this.inputUsername.setValue(username)
        await this.inputPassword.setValue(password)
        await this.btnSubmit.click()
    }

    public open () {
        return super.open('login')
    }
}

export default new LoginPage()

Two WebdriverIO details matter here.

Selectors are getters that return an un-awaited $. get inputUsername() returns $('#username') without await, and nothing is sent to the browser at that point. The lookup happens when a command such as setValue() is called on it, and that is when auto-waiting applies. So a spec can touch LoginPage.btnSubmit before the page is even open, and the getter costs nothing until it is used. Getters are the WebdriverIO convention (the starter generates them) because they keep the selector next to its name and make every access a fresh, lazy lookup.

WebdriverIO is forgiving here: if you do store an awaited element and the page reloads, the next command re-runs the element's selector rather than failing with a stale element error, as a check on WebdriverIO 10.2.0 confirmed. The getter style still reads better and does not depend on that recovery.

The import ends in .js, not .ts. The project is an ES module, and Node.js resolves ES module imports by the path of the compiled file. The starter's tsconfig.json is set up for this; write .js even though the file on disk is .ts.

The file exports an instance (new LoginPage()), not the class. A spec imports it and uses it directly. Page objects hold no state between tests here, so one shared instance per worker is enough.

A getter is written as get btnSave () { return $('#save') }. A colleague worries that reading Page.btnSave before the page has loaded will fail. What actually happens?

An un-awaited $ is a lazy query. It is resolved when you call a command or pass it to an expect matcher, which is also when WebdriverIO waits for the element to exist.

Actions return nothing, specs assert#

test/pageobjects/secure.page.ts:

import { $ } from '@wdio/globals'
import Page from './page.js'

class SecurePage extends Page {
    public get heading () {
        return $('h2')
    }

    public get btnLogout () {
        return $('*=Logout')
    }

    public async logout () {
        await this.btnLogout.click()
    }
}

export default new SecurePage()

Note what the page objects do not contain: assertions. login() performs the steps; whether the login should have worked is the spec's decision. That way one login() serves both the "valid credentials" and the "wrong password" test.

The spec#

Replace test/specs/login.e2e.ts with:

import { expect } from '@wdio/globals'
import LoginPage from '../pageobjects/login.page.js'
import SecurePage from '../pageobjects/secure.page.js'

describe('Login', () => {
    beforeEach(async () => {
        await LoginPage.open()
    })

    it('logs in with valid credentials and out again', async () => {
        await LoginPage.login('tomsmith', 'SuperSecretPassword!')

        await expect(SecurePage.heading).toHaveText(expect.stringContaining('Secure Area'))
        await expect(SecurePage.flash).toHaveText(
            expect.stringContaining('You logged into a secure area!'))

        await SecurePage.logout()
        await expect(LoginPage.flash).toHaveText(
            expect.stringContaining('You logged out of the secure area!'))
    })

    it('shows an error for a wrong password', async () => {
        await LoginPage.login('tomsmith', 'wrong')

        await expect(LoginPage.flash).toHaveText(
            expect.stringContaining('Your password is invalid!'))
        await expect(LoginPage.inputUsername).toBeDisplayed()
    })
})

The page objects return elements (SecurePage.heading) and the spec passes them to expect, so the matchers keep their retrying behaviour. A page object method such as async getHeadingText() that returns a string would throw that away, for the reason shown in chapter 4.

A teammate adds async isLoggedIn () { return (await $('h2').getText()).includes('Secure') } to the page object and asserts expect(await SecurePage.isLoggedIn()).toBe(true). What is the problem?

Turning page state into a boolean in the page object removes the retry. Return the element (or a locator getter) and let an expect-webdriverio matcher wait for the expected state.

Run it#

npx wdio run wdio.conf.ts --spec test/specs/login.e2e.ts
[chrome 157.0.8103.78 mac #0-0] Login
[chrome 157.0.8103.78 mac #0-0]    ✓ logs in with valid credentials and out again
[chrome 157.0.8103.78 mac #0-0]    ✓ shows an error for a wrong password
[chrome 157.0.8103.78 mac #0-0]
[chrome 157.0.8103.78 mac #0-0] 2 passing (3.1s)

You now have four spec files: login, selectors, waiting and assertions. The next chapter runs all of them on browsers you do not have installed.