Using Typescript with Protractor for Dropdown Menus

As a newcomer to Protractor, I am looking to automate the selection of a dropdown. While I have some knowledge in JavaScript, I am currently working with typescript. Can someone advise me on how to select the dropdown option based on the text provided?

For example:

<ul class="ui-dropdown-items ui-dropdown-list ui-widget-content ui-widget ui-corner-all ui-helper-reset ng-tns-c46-10 ng-star-inserted" style="">
                        <!---->
                        <!----><!---->
                            <!---->
                            <!----><li class="ng-tns-c46-10 ui-dropdown-item ui-corner-all ng-star-inserted">
                                <!----><span class="ng-tns-c46-10 ng-star-inserted">Value 1</span>
                                <!---->
                            </li><li class="ng-tns-c46-10 ui-dropdown-item ui-corner-all ng-star-inserted">
                                <!----><span class="ng-tns-c46-10 ng-star-inserted">Value 2</span>
                                <!---->
                            </li><li class="ng-tns-c46-10 ui-dropdown-item ui-corner-all ng-star-inserted">
                                <!----><span class="ng-tns-c46-10 ng-star-inserted">Value 3</span>
                                <!---->
                            </li>


                        <!---->
                        <!---->
                    </ul>

My main query is regarding how I can choose the dropdown value by matching it with the visible text.

Answer №1

While there may be more efficient methods available, the following code offers a quick workaround:

object class `getDropDown() {
                   return element(by.className('the class you assign to the dropdown');

Then in your spec class:

`it('should select an element in the drop down), () => {
                             page.navigateTo(); 
                             page.getDropDown().sendKeys(Key.DOWN)
                             page,getDropDown().sendKeys(Key.RETURN)`

Although this approach may not be the most ideal solution, it is straightforward and functional. If you need to select a specific item from a large list of items within the dropdown, consider modifying the code above to use

sendKeys('whatever item you need')
. This modification can be useful for scenarios where selecting a particular li element in a form is necessary for validation purposes. Keep in mind that this method may not be applicable if your form does not support manual typing into the dropdown field.

Answer №2

To achieve this, you can follow these steps:

// locating the combobox
let container = element(by.css('ul'));
// selecting an option
container.element(by.cssContainingText('value 1')).click();

If you wish to automate this process, you can create a wrapper class. Here's an example tailored to your scenario:

import { browser, element, by, ElementArrayFinder, ElementFinder, Locator } from 'protractor';
import { By } from 'selenium-webdriver';
import { ProtractorLocator } from 'protractor/built/locators';

const locators = {
  byText: (text: string) => by.cssContainingText('li', text)
};

export class ListWrapper {

  constructor(private container: ElementFinder) {
    // for instance: let container = element(by.css('ul'))
  }

  public async selectByText(text: string): Promise<void> {
    await this.findChild(locators.byText(text)).click();
  }

  public findChild(locator: By | Locator): ElementFinder {
    return this.container.element(locator);
  }

}

Subsequently, in your test script, you can implement the following:

let listWrapper = new ListWrapper(element(by.css('ul')));
await listWrapper.selectByText('Value 1');

Please note that I have not conducted a test on this yet, but it should function correctly as I employ a similar methodology.

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

Next.js API route is showing an error stating that the body exceeds the 1mb limit

I'm having trouble using FormData on Next.js to upload an image to the server as I keep getting this error. I've tried various solutions but haven't been able to resolve it yet. This is my code: const changeValue = (e) => { if (e.target ...

Having difficulty integrating framer-motion with react-router

I've been working on adding animations and smooth transitions to my app using Framer-motion, but I'm facing some challenges in getting it all to function properly. With react-router 6, my goal is to trigger exit animations on route sub-component ...

Develop a radio button filter utilizing the "Date of Creation" attribute, implemented with either jquery or JavaScript

I am currently utilizing a customized Content Query Web Part to load a series of list items. Each of these items has an XSLT attribute known as the Created Date. Shown below is an example of the markup: <div class="item" createddate="2014-01-22 13:02 ...

The return type of Array.find is accurate, however, it contains an error

Trying to find a way to indicate the expected return type of Array.find() in TypeScript, I encountered an incompatibility warning. View code in playground class A { "type"="A" t: string; #a = 0 constructor(t: string) { ...

Making an Ajax request using jQuery to retrieve content in the application/x-javascript format

Can anyone help me figure out how to retrieve the content of "application/x-javascript" using a jQuery Ajax call? I keep getting null content and I'm not sure why. This is what I have been attempting so far: $.ajax({ dataType: "json", ...

Combining NPM Script Commands: A Comprehensive Guide

I am aware that NPM scripts can be chained using &&, pre-, and post- hooks. However, I am wondering if there is a way to simply break down lengthy script lines into a single, concatenated line? For instance, can I convert the following: "script": ...

What are the best methods for repairing a malfunctioning Drawer?

My template can be found here: SANDBOX When transitioning to a nested route, I am experiencing a double rendering issue which causes the DRAWER to reopen. How can this be fixed? You can observe this effect in the "NESTED" tab. It is important that the fi ...

Uh-oh! A circular dependency has been detected in the Dependency Injection for UserService. Let's untangle this web and fix the issue!

Encountering the following error: "ERROR Error: Uncaught (in promise): Error: NG0200: Circular dependency in DI detected for UserService." The auth.component.ts utilizes the UserService and User classes, while the user.service.ts only uses the User class. ...

Using Express.js to leverage Vega for generating backend plots

Exploring ways to create plots using backend code and transfer them to the front end for display. Could it be feasible to generate plots on the server-side and then transmit them to the front end? I am interested in implementing something similar to this: ...

Enhancing interface properties with type safety in a function declaration using Typescript

Consider the following scenario: interface Steps { stepOne?: boolean; stepTwo?: boolean; stepThree?: boolean; } let steps: Steps = {}; function markStepDone (step: ???) { steps[step] = true; } markStepDone('anything'); Is there a wa ...

Creating custom designs for a HTML button using CSS

Within an HTML form, there are two buttons set up as follows: <button kmdPrimaryButton size="mini" (click)="clickSection('table')">Table View</button> <button kmdPrimaryButton size="mini" (click)=&quo ...

Verify if Angular 2 route parameters have a legitimate value

Within an angular2 component, I have the following code: ngOnInit() { this.route.params .switchMap((params: Params) => this.elementsService.getElement(+params['id'])) .subscribe(element => { this.elementToEd ...

Use JQuery to gradually decrease the opacity of divs individually

I am currently working on a function that fades out all divs except the one that has been clicked on simultaneously. However, I want them to fade out one by one instead. Additionally, I would like the divs to fade out in a random order. If anyone knows ho ...

Including a unicode escape sequence in a variable string value

I'm struggling to find the right way to include a unicode escape in a dynamic string value to display emojis in React. My database stores the hexcode for the emoji (1f44d) I have set up a styled-component with the necessary css for rendering an emoj ...

Sharing information through a hyperlink to a Bootstrap popup window

I've been attempting to send data to a Bootstrap modal window with no success so far. First, I tried: <a href="#TestModal?data=testdata" role="button" class="btn" data-toggle="modal">Test</a> However, the modal did not open as expected. ...

Adjusting the properties of an element with Javascript

My goal is to dynamically set the value of a parameter within a <script> element using JavaScript. I am using the Stripe checkout.js and I want to populate the Email input field with a value obtained from another text box on the page. Here's how ...

Modify the color of the components in Select from Material-UI

After reviewing numerous questions and answers on this topic, I have yet to find a suitable solution for my issue. Seeking guidance from the community for assistance. Utilizing the Select component from @mui/material to showcase the number of records per ...

Chrome: When enlarging an image, the overflow of the outer div is disrupted

My image wrapper is designed to hide overflow when hovered over. It works well in Firefox and Opera, but Chrome displays it strangely. I've created a 10-second screen recording to demonstrate the issue. Watch it here: I also tested it on JSFiddle, ...

Node and Express Fundamentals: Delivering Static Resources

const express = require('express'); const app = express(); app.use(express.static('public')); I've been attempting to complete the "Basic Node and Express: Serve Static Assets" challenge on freecodecamp, but it keeps showing as " ...

sending information to PHP through AJAX dynamically

I implemented a registration form that utilizes function user_reg(user_name,user_email,user_pswd) { var serverpath=window.location; alert(serverpath); var dataString = 'name='+ user_name + '&email=' + user_email + '&psw ...