Generic functions help me to reduce the amount of Playwright test automation code

Published on November 12, 2024

One of the challenges in writing automated tests is to have a low maintenance cost of the tests. Creating a library of functions in a Page Object Model helps because the test can reuse the functions in the library. Typescript generic functions within my Playwright Page Object Model also help me, in some situations, to reduce the amount of code the tests require. 

A generic function can be used with many types so one function can have many uses. The image below shows a class containing functions that log a player’s name and position in their team. The class includes a function that logs the name and position of a footballer and a second function that logs the name and position of a cricketer. The class also contains a generic function that logs the name and position of a player that can be used for a cricketer or a footballer. When a function is generic, it has a “type hole” shown with <> and must be filled by a type. The type in the function definitions below is shown by the letter T. The non-generic functions have a parameter of position that takes a type of either footballer or cricketer. The type of the parameter named position is passed to the generic function via T.

The types of footballer and cricketer are in the file lib.sport.d.ts shown below

Types are more powerful than strings because the types are validated, for example, if I try to give a footballer a cricketer’s position an error is returned:

When the functions are called in the test the type is passed to the function logPlayer(), see below:

When the test is executed the output from the two functions is the same:

The generic function logPlayer() can replace the functions logCricketer() and logFootballer() so I only need one function instead of two. This means that there is less code to maintain.

If the product being tested increases in scope, for example, if this application needs to support rugby players, you need not add a new function to support rugby players. You can, for example, add a rugby player type and use the logPlayer() function.

The generic function also creates a consistent interface, making the tests easier to read. The same logPlayer() function is used for every type of player.

Generic functions are a form of modelling. Cricketers and footballers are both types of players, so they can be modelled in a generic function that models cricketers and footballers as players. Where this form of modelling is useful generic functions are helpful.

This blog post contains a very simple example of a generic function. Generic functions can reduce the maintenance required for test automation by reducing the code you must maintain. Are there places in your test automation code where generic functions would help you?

I learned about generic functions on Execute Program: https://www.executeprogram.com/courses/typescript-basics/lessons/generic-functions