Implementing try-catch logic for element visibility in Playwright using TypeScript poses limitations

There is a specific scenario I need to automate where if the title of a page is "Sample title", then I must mark the test as successful. Otherwise, if that condition is not met, I have to interact with another element on the page and verify if the title changes to "Sample title".

My Approach: I attempted to handle this using a try-catch block, but unfortunately, I kept encountering timeout errors. Here's a snippet of the code I used:

try {
    await expect.soft(page).toHaveTitle("Sample title",{ timeout: 30000 })
}
catch (error){
    await page.getByRole('link', { name: 'here' }).click();
    await expect.soft(page).toHaveTitle("Sample title",{ timeout: 30000 })
}

I anticipated that the script would first attempt the code in the try block, and upon encountering a timeout error, it would proceed to the catch block. However, the execution never goes to the catch block, resulting in the following error message:

Error:

Test timeout of 30000ms exceeded.

Error: expect(locator).toHaveTitle(expected)

Locator: locator(':root')
Expected string: "Sample title"
Received string: "Different Title"
Call log:
  - expect.soft.toHaveTitle with timeout 30000ms
  - waiting for locator(':root')
  -   resolved locator to <html>…</html>
  -   unexpected value "dfretgrt"
...

> 19 |
20 |   try {
21 |     await expect.soft(page).toHaveTitle("Sample title",{ timeout: 30000 })
       |                             ^
22 |
23 |   }
24 |   catch (error){

Answer №1

Try using the "OR" locator method.

This feature creates a unique locator that can match either of two locators, which can be helpful in various scenarios, including yours.

Example of How to Use It

Imagine a situation where you want to click on a button labeled "New email," but sometimes a security settings window pops up instead. With the "OR" locator, you can wait for either the "New email" button or the dialog to appear and take appropriate action.

const newEmail = page.getByRole('button', { name: 'New' });
const dialog = page.getByText('Confirm security settings');
await expect(newEmail.or(dialog)).toBeVisible();
if (await dialog.isVisible())
  await page.getByRole('button', { name: 'Dismiss' }).click();
await newEmail.click();

For more information, visit:

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

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

Creating and Injecting Singleton in Angular 2

I have a custom alert directive set up in my Angular app: import { Component } from 'angular2/core'; import { CORE_DIRECTIVES } from 'angular2/common'; import { Alert } from 'ng2-bootstrap/ng2-bootstrap'; @Component({ sele ...

The Typescript module in question does not contain any exported components or functions related to

I've encountered an unusual issue while working on a React, Redux TypeScript application. It seems that after making some changes, one of the modules has stopped exporting its members. Here is the folder structure: src |---- components |---- contain ...

The InAppBrowser seems to have trouble loading pages with cookies when I attempt to navigate back using the hardware back button

In my Ionic/Angular application, I utilize the InAppBrowser plugin to access a web application for my company. The InAppBrowser generally functions properly; however, there is an issue with a cookie within the web application that controls filters for cert ...

Is it possible to choose a range in ion2-calendar starting from the day after tomorrow and spanning three months ahead?

Currently, I have set up an ion-calendar utilizing the ion2-calendar plugin. The calendar is configured to disable dates prior to today's date. However, my goal is to also disable "today" and display available dates starting from tomorrow. Additionall ...

An array devoid of elements may still hold significance

I have a specific function structure as follows: public returnData(): { points: Array<{ x: number, y: number }>, pointsCount: Array<number> } { return { points: [{x: 0, y: 1},{x: 1, y: 2 }], pointsCount: [1, 2, 3, 4] } ...

Sharing a variable between an Angular component and a service

I am attempting to pass a variable from a method to a service. from calibration-detail.component.ts private heroID: number; getTheHeroID() { this.heroService.getHero(this.hero.id).subscribe(data =>(this.heroID = data.id)); } to step.service.ts I ...

Discover the subsite inventory of a SharePoint site using TypeScript

Is there a way to gather all sub-sites from my SharePoint site and organize them into a list? I initially thought of using this.context.pageContext, but could not locate it. Please excuse my seemingly simple question, as I am still learning TypeScript. ...

What is the process for generating an index.d.ts file within a yarn package?

I'm facing an issue with creating the index.d.ts file for my yarn package. Here is my configuration in tsconfig.json: { "include": ["src/**/*"], "exclude": ["node_modules", "**/*.spec.ts"], " ...

Encountering unanticipated breakpoints in compiled .Next files while using Visual Studio Code

As a newcomer to NextJS, I have encountered an issue that is disrupting my workflow. I followed the instructions in https://nextjs.org/docs/advanced-features/debugging#using-the-debugger-in-visual-studio-code to set up my launch.json file. Although I am ...

Can you explain how the "reduce" function can be implemented using an interface in TypeScript?

Can you explain the "reduce" function using an interface in TypeScript? https://i.stack.imgur.com/X1VxL.png ...

Parsing error encountered while trying to handle an unexpected token at line 214, character 33. It appears that an appropriate loader is missing to process this particular file type

I've been developing a Typescript React project for the past few months without any issues. However, things took a turn yesterday when I decided to run npm audit fix and npm audit fix --force in order to address some security concerns that appeared ou ...

app-root component is not populating properly

As a newcomer to Angular 2, I have embarked on a small project with the following files: app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { MaterialModule } fro ...

Open new tab for Angular OAuth2 OIDC login process

Currently, I am incorporating the authorization code flow using angular-oauth2-oidc in my Angular application. It is a fairly straightforward process. However, I would like to have the ability for the login flow to open in a new tab when the login button ...

Typedoc: only export contents from a particular file are documented

Currently, I am working on developing two npm packages: https://github.com/euberdeveloper/mongo-scanner https://github.com/euberdeveloper/mongo-cleaner My goal is to create documentation for these packages using Typedoc. The main file is index.js p ...

What could be the reason for the crash caused by ngModel?

The usage of [(ngModel)] within a *ngFor-Loop is causing an endless loop and crashing the browser. This is how my HTML looks: <div class="container"> <div class="row" *ngFor="let item of controlSystemTargetViewModel.values; let index = i ...

forwarding within afterCallback employing nextjs-auth0

I need to handle multiple cases for redirecting users based on various fields and custom claims in the user token, which involves navigating through complex if/else blocks. Let's consider a simpler example where I want to redirect the user to /email- ...

Tips for sharing data between two components

In my project, I have a customized Shared Component which consists of an input search bar with a "continue" button. This Shared Component is being utilized within two other components - the buy component and sell component. The challenge I am encountering ...

Creating a dynamic columns property for Mat-Grid-List

Is it possible to create a Mat-Grid-List where the number of columns can be dynamically changed based on the width of the container? Here is an example: <mat-grid-list [cols]="getAttachmentColumns()" rowHeight="100px" style="width: 100%;"> <mat ...

Navigating through alterations in intricate data utilizing the BehaviorSubject concept

If I have a Service that offers a BehaviorSubject to any component needing the most up-to-date version of certain data, how can these components differentiate what changed in the data when they receive notifications? export class DataService { pri ...