Checking the selected option in a dropdown using Playwright

I have been working on validating the dropdown value I selected using Playwright. However, I encountered an error while writing the code for validation. Does anyone know how to resolve this issue and write it in TypeScript using $eval? Thank you.

test('dropdown validation',async ({page}) => {
    await page.goto('https://the-internet.herokuapp.com/dropdown');
    await page.selectOption('#dropdown','1');
    const selectvalue = await page.$eval('#dropdown',(element)=>element.value);
   expect (selectvalue).toContain('1');


Error: expect(received).toContain(expected) // indexOf

Expected substring: "1"
Received string:    "select"

  22 |    // const alloption=await option1.$$('option');
  23 |    await page.locator('select').selectOption('1');
> 24 |    await expect('select').toContain('1')
     |                           ^
  25 |
  26 | 

Answer №1

There were some similar challenges on that particular page where the speed fluctuated and defaulted to select, causing the code to change the dropdown values afterwards. In such cases, a hard wait can be employed.

page.waitForTimeout(100)

Alternatively:

selectedDropdownText = page.locator('#dropdown [selected="selected"]');
textToVerify = selectedDropdownText.innerText();

Or for the value:

   await this.page.$eval<string, HTMLSelectElement>('select[id="dropdown"]', (element) => element.value);

Answer №2

Utilize the assess

locator.evaluate("el => el.options[el.selectedIndex].value")

Answer №3

If you're looking to confirm the value of a selected option, consider utilizing the toHaveValue method.

This function verifies that the selector contains the specified value.

Following the latest recommendations from Playwright documentation, this is the suggested approach.

await expect(locator).toHaveValue(expValue);

This line of code checks if the selector indeed holds the expected value.

To check for specific text within a locator:

await expect(locator).toHaveText(/Welcome, Test User/);

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

Testing the React component with the useRouteMatch hook by running a unit test

Consider the code snippet below: import React, { useState, useEffect } from 'react'; import { createPortal } from 'react-dom'; import { useRouteMatch, Link } from 'react-router-dom'; interface MyComponentProps { myId?: stri ...

Tips for merging individual Koa-Routers using Typescript

My approach to organizing routers in my project involved categorizing them based on their purpose. Here's how they are structured: routers/homeRouter.ts import * as Router from 'koa-router'; const router: Router = new Router(); router ...

What is the best way to create a highlighted navigation bar using Angular 2?

Is there a way to keep the navbar active even after refreshing the page in Angular 2? I am currently using CSS to accomplish this, but the active tab is removed upon page refresh. Any suggestions on how to tackle this? HTML:-- <ul class="nav navbar- ...

Is it possible to update the text within a button when hovering over it in Angular?

https://i.sstatic.net/ZhNeM.png https://i.sstatic.net/kb670.png I'm looking to update the text displayed inside a button when hovering over it, similar to the examples in these images. I have already implemented the active state, but now I just need ...

Enable child classes to overwrite using either a function attribute or a method

class Foo { foo: () => void } class Bar extends Foo { foo() {} } Is there a way in which TypeScript can be configured to allow the scenario described above? Playground The 'Foo' class defines a property 'foo' as an instance ...

Performing Cypress testing involves comparing the token stored in the localStorage with the one saved in the clipboard

I am currently working on a button function that copies the token stored in localStorage to the clipboard. I am trying to write code that will compare the token in localStorage with the one in the clipboard in order to verify if the copy was successful. H ...

Ways to specify the T (Generic type) associated with the class

I am working with a class that uses a generic type like this: SomeGenericClass<T>{ constructor(){ } } Within some of the functions, I log messages and want to refer to the current type T of the generic class in my logs. I have attempted t ...

Is your Angular Bootstrap Modal component failing to function properly?

I've been attempting to implement Modals from Bootstrap for Angular, however, I'm encountering some issues. Here is the link to the documentation: I followed the instructions and copied the code for the 'Global configuration of modals' ...

Issues with NPM start arise moments after incorporating create react app typescript into the project

I've encountered an error while trying to initiate my create react app with Typescript. Despite following all the necessary steps, including adding the .env file (with SKIP_PREFLIGHT_CHECK=true) and updating/reinstalling NPM, I keep facing this issue. ...

Guide on implementing a .catch method in Firebase's onSnapshot function

I have recently developed an Ionic Firebase chat application. I seem to be encountering an issue with setting up a query snapshot when initializing the message page. Here is the code snippet that I am using: ngOnInit() { this.messageService.getA ...

The challenge of maintaining focus in Internet Explorer while running Selenium webdriver scripts

Initially, I need to hover over the element to trigger a dropdown and then click on a specific link. This functionality works smoothly in Firefox and Chrome but encounters an issue in Internet Explorer. Below is the snippet of code being used: WebElement ...

Using Typescript to implement Markdown in React

Seeking a solution to implement Markdown parsing in React using Typescript. I am exploring methods such as: import * as ReactMarkdown from 'react-markdown' // OR import ReactMarkdown = require('react-markdown') However, encountering ...

Incorrect positioning of AnyChart within a reusable component (Angular version 9.1.3, Bootstrap 4.4.1, Anychart version 8.7.1) causing display issues on the DOM

I have created a test dashboard featuring two Bootstrap cards, each containing an Anychart column chart. The primary objective is to experiment with reusable components. For those interested, here is the code link on Stackblitz Upon running the code, my ...

TypeScript: Unforeseen reserved term

In my WebStorm IDE & Node.js project, I successfully utilized a file called "mongo-manager.ts" in the routes\index.js file without any issues. However, I made two changes: Instead of ignoring WebStorm's prompt to compile TypeScript to JavaScrip ...

Optimizing an ASP.NET web application for seamless integration with Angular 2 and TypeScript

For the past couple of days, I have been delving into angular2. I am curious to understand the process of configuring my project to effectively utilize angular2 and typescript. My development environment is Visual Studio 2015. Can you guide me on the nec ...

Converting Enum into an array in TypeScript to return the keys of the Enum

After defining the following enum: export enum Types { Type1 = 1, Type2 = 2, ... } We can create an array based on this enum with the function below: export function EnumKeys<T>(obj: object): string[] { return Object.keys(obj) ...

Utilizing Nativescript: Understanding the equivalence of path & svg tags in Angular and how to effectively implement them

How can I programmatically use dynamic SVG images in Nativescript-Angular, rather than displaying pre-generated ones? While Angular allows for easy manipulation using svg and path, doing the same in a Nativescript app doesn't seem to render correctly ...

ts-node is having trouble locating the npm package discord-api-types

Encountering an issue while running the discord.js file deploy-commands.ts using the command ts-node deploy-commands.ts, where ts-node generates the following error: Error: Cannot locate module 'discord.js/node_modules/discord-api-types' Require ...

AngularJS 2 TypeScript structure

My application includes a user service for managing user operations and an interface for the user object. user.service.ts import {Injectable} from 'angular2/core'; export interface User { name: string; email?: string; picture?: string; } ...

Bug in auto compilation in Typescript within the Visual Studios 2015

Currently, I am utilizing Visual Studio Pro 2015 with auto compile enabled on save feature. The issue arises in the compiled js file when an error occurs within the typescript __extends function. Specifically, it states 'Cannot read property prototyp ...