Tips for creating a custom waitForElementText function in Playwright

I need to implement a function called waitForElementText() in playwright.

For example, I have headers labeled with the CSS selector '.header-name' on each page.

When navigating from the Home page to the Users page,

I provide two parameters to the method:

waitForElementText(locator: string, expectedText: string)

The goal is to wait for the header name to change from "Home" to "Users".

Although I attempted using the page.waitForFunction() method, I encountered this error:

page.waitForFunction: TypeError: Cannot read properties of undefined (reading 'locator')

Answer №1

With Playwright's locator's API automatically waiting for elements and featuring a text-based selector, the waitForText function is already included in the API under getByText:

await page.getByText("Users"); // for a substring match

// or an "exact" match (after whitespace normalization):
await page.getByText("Users", {exact: true});

// or as an assertion:
await expect(page.getByText("Users", {exact: true})).toBeVisible();

If this does not provide enough specificity to identify the element, you can chain locators:

const playwright = require("playwright"); // ^1.39.0

const html = `<!DOCTYPE html><html><body>
<h1 class="header-name">  Users  </h1></body></html>`;

let browser;
(async () => {
  browser = await playwright.firefox.launch();
  const page = await browser.newPage();
  await page.setContent(html);
  await page
   .locator(".header-name")
   .getByText("Users", {exact: true})
   .waitFor();
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

Answer №2

Try using the auto-retrying assertion method toHaveText

This feature will keep trying until the Locator locates an element with the specified text. You can even utilize regular expressions to match the text.

const locator = page.locator('.title');
await expect(locator).toHaveText(/Welcome, Test User/);
await expect(locator).toHaveText(/Welcome, .*/);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can callback argument types be contingent on certain conditions? For example, could argument 0 be null if argument 1 is a string?

I am attempting to implement conditional type logic for the parameter types of a callback function. In this scenario, the first argument represents the value while the second argument could be an error message. type CallbackWithoutError = (value: string, ...

Guide to accessing the content of pure ES6 modules directly in the Chrome console without the need for Webpack

Situation: When using tsc to compile code for es6, the scripts function properly once they are served from a server. However, I am unsure of how to access variables within modules through the console. The file names do not seem to be available as objects ...

Angular 13: How to Handle an Empty FormData Object When Uploading Multiple Images

I attempted to upload multiple images using "angular 13", but I'm unable to retrieve the uploaded file in the payload. The formData appears empty in the console. Any suggestions on how to resolve this issue? Here is the HTML code: <form [formGro ...

The array remains undefined even after being assigned within the subscribe function

I have encountered an issue in my Angular app where the array productLocations is being assigned in the ngOnInit method within a subscription, but it remains undefined when used in another method. Despite following advice on Stackoverflow to move the assig ...

Retrieve the :id parameter from the URL as a numerical value in Node.js using Typescript

Is there a way to directly get the :id param from the URL as a number instead of a string in order to easily pass it on to TypeORM for fetching data based on a specific ID? Currently, I am using the following approach where I have to create an additional ...

Issue with Nestjs validate function in conjunction with JWT authentication

I am currently implementing jwt in nest by following this guide Everything seems to be working fine, except for the validate function in jwt.strategy.ts This is the code from my jwt.strategy.ts file: import { Injectable, UnauthorizedException } from &ap ...

Duplicate the ng-template using ng-content as the body (make a duplicate of ng-content)

I have been working on creating a feature that allows users to add custom columns to a PrimeNg table. The main reason for developing this feature is to provide users with a default table that already has numerous configuration options pre-set. However, I ...

Unable to determine all parameters for Modal: (?, ?, ?)

import { Component, Inject } from '@angular/core'; import { NavController, Modal } from 'ionic-angular'; import { PopupPage } from '../../components/modal/modal.page'; @Component({ templateUrl: 'build/pages/spot/spot. ...

Is it time to refresh the package-lock.json file?

I'm currently in the process of updating a React app from Node 14 to 16. One step I took during the upgrade was deleting the node_modules folder and package lock, then generating a new package-lock.json file. However, this resulted in numerous compila ...

Cheerio fails to retrieve items from the specified directory

My main goal with cheerio is to scrape the titles from this IMDb ranking: Despite following the documentation and specifying the exact HTML path for the titles, I am getting back random and confusing objects like: 'x-attribsNamespace': [Object ...

Can one create a set of rest arguments in TypeScript?

Looking for some guidance on working with rest parameters in a constructor. Specifically, I have a scenario where the rest parameter should consist of keys from an object, and I want to ensure that when calling the constructor, only unique keys are passed. ...

Utilizing vue-property-decorator: Customizing the attributes of @Emit

After seeing the @Emit feature, I checked out the example on GitHub. import { Vue, Component, Emit } from 'vue-property-decorator' @Component export default class YourComponent extends Vue { count = 0 @Emit() addToCount(n ...

What is the solution for this problem in TypeScript involving an API service call?

Trying to utilize the API Service to fetch data and display the response as an object created by a class constructor Currently executing a Typescript code that interacts with the API Service import * as request from "request"; import { Users } from "./Us ...

Creating a TypeScript rule/config to trigger an error when a React Functional Component does not return JSX

I've encountered a recurring issue where I forget to include a return statement when rendering JSX in a functional component. Here's an example of the mistake: const Greetings = function Greetings({name}) { <div>Greetings {name}</div& ...

What are the steps to access a query parameter within an API route.js file using the latest App routing strategy?

Here is the goal I am aiming for: Utilize Next.js with App router. Establish a backend route /api/prompt?search=[search_text] Retrieve and interpret the search query parameter in my route.ts file. Based on the search parameter, send back data to the front ...

Initiate and terminate server using supertest

I've developed a server class that looks like this: import express, { Request, Response } from 'express'; export default class Server { server: any; exp: any; constructor() { this.exp = express(); this.exp.get('/' ...

What prevents `console.log` from working within a button click event?

Why is this not functioning correctly? <button (click)="console.log('ok');">Display Details</button> The error message reads: Cannot read property 'log' of undefined However, a console.log statement in the class construc ...

TypeScript implementation of internationalization message extraction in Create React App

I am facing challenges in getting i18n messages extracted, as defined by react-intl's defineMessages, to function correctly in a TypeScript-based CRA. Here are the methods I've attempted: Initial Approach I tried following this guide to make i ...

Invoke a function of a child component that resides within the <ng-content> tag of its parent component

Check out the Plunkr to see what I'm working on. I have a dynamic tab control where each tab contains a component that extends from a 'Delay-load' component. The goal is for the user to click on a tab and then trigger the 'loadData&apo ...