Protractor end-to-end tests: extracting chosen menu item from page model function

My website has a navigation menu with different items. I'm using a page model for end-to-end tests.

In one of my test specs, I need to call a function from the page model that does the following:

  • Check that only one item in the menu has a specific class
  • Return the index of that item

This is a snippet of my code:

describe('Main screen and global navigation', () => {
    class MainPage {
        load() {
            browser.get('');
        }

        getMainMenuActiveItemIndex(): number {
            let list = element.all(by.css('ul.menu li'));
            // Need help iterating through
            return 0;
        }

        navigate(itemClass: string) {
            let menuItem = element(by.css('ul.menu li.' + itemClass));
            menuItem.click();
        }
    }

    let p = new MainPage();

    beforeEach(function () {
        p.load();
    });
    it('should navigate to subpages', () => {
        expect(p.getMainMenuActiveItemIndex()).toBe(0);
        p.navigate('invoices');
        expect(p.getMainMenuActiveItemIndex()).toBe(1);
    });
})

I understand that element... returns a promise. However, I'm unsure how to resolve the promise before returning a value from the function.

Should I return a promise from the function instead of just a number?

Answer №1

Here is the correct method to accomplish this task:

 findActiveMenuItemIndex() {
     return element.all(by.css('ul.menu li')).getAttribute('class').then((classArray) => {
          for (let i = 0; i < classArray.length; i++){
            if (classArray[i].includes('active')){
                 return i;
              }
          }
          return -1; // Return -1 if no 'li' element has the class 'active'
       })
    }

Answer №2

Simply return the promise and let Protractor's expect() handle it for you. No need to use a then() function.

If you need more clarification, feel free to ask.

Edit 1: It looks like you received the answer from @sudharsa. I recommend using the filter function instead of the then function in getMainMenuActiveItemIndex().

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

a tutorial on linking component data to a prop value

Is there a way to connect the searchString value in my Vue component to the item value in the html template it uses? I need to pass this value to the method called in my Ajax request. Vue: Vue.component('user-container-component', { props: ...

Creating a grid with individual node delays in CSS animations using ReactJS

Struggling with a CSS animation issue in ReactJs. I suspect the problem, but unsure how to solve it. I'm rendering a 5x5 grid and displaying it using this function: DisplayNodes = () => { const {grid} = this.state; // get the node array fro ...

Angular CLI yields a unique arrangement of files

As a newcomer to angular2, I have been exploring various tutorials to enhance my knowledge. The tutorials I've been following have a specific file structure, as shown below: Link to tutorial corresponding to the image below: https://i.sstatic.net/7s ...

Sending data to mongodb using the fetch API and FormData method is a simple process that involves constructing

I have been trying to send data to mongoDB using the fetch API along with FormData, but encountering an error: POST https://xxxxxxxxxxxxxxxxxxxxxxxx/upload 500 (Internal Server Error) The form data in my EJS file appears as follows: <div id=" ...

The <b-list-group-item> component in a Vue.js CLI application using bootstrap-vue is failing to render

My Vue-CLI app uses Bootstrap-vue and axios to fetch JSON data. The HTML code in my App.vue displays the data using UL and LI tags: <p v-if="loading">Loading...</p> <ul v-else> <li v-for="(value, key) in post" :key="key"> ...

Splitting an array into multiple arrays with distinct names: A step-by-step guide

I have a data set that looks like this: [A,1,0,1,0,1,B,1,0,0,1,A,1]. I want to divide this array into smaller arrays. Each division will occur at the positions where "A" or "B" is found in the original array. The new arrays should be named with the prefix ...

Encountering a 401 Unauthorized error while using the Post method with Angular 2 on the frontend and CakePHP 3 on the backend

Using Angular 2 for both the Front end and Back end within Cakephp 3, encountering a 401 Unauthorized status error during the login process. Although JWT has been configured in Cakephp 3 and works well in POSTMAN, it fails to work seamlessly with Angular. ...

Ways to determine if a JSON value that was returned is null

Is there a way to determine if the value of a JSON object is null? I am looking to show an image upload form if info.pic is null, otherwise display the image fetched from the JSON. Here is my HTML code snippet: <div class="col-sm-9" *ngFor="let info o ...

Arranging cards in a stack using VueJS

I am currently working with a small vue snippet. Originally, I had v-for and v-if conditions in the snippet, but due to issues reading the array, it is now hardcoded. The current setup produces three cards stacked on top of each other. I am exploring opti ...

Supporting multiple types for matching object structures is a feature in Jest

I'm currently working on a test using jest to verify if an object key is either a string or a number. It seems like a basic task, but surprisingly there isn't much guidance in the documentation. Test Example: test('Checking asset structure ...

The element type 'HTMLElement' does not contain a property named 'pseudoStyle'

Currently experimenting with adjusting the height of a pseudo element using Typescript. An error is popping up in my IDE (vscode) as I go along. This is the code snippet I am working with. // choose element let el: HTMLElement = document.getElementById( ...

Tips on preventing repeated data fetching logic in Next.js App Routes

I'm currently developing a project with Next.js 13's latest App Routes feature and I'm trying to figure out how to prevent repeating data fetching logic in my metadata generation function and the actual page component. /[slug]/page.tsx expo ...

How can I utilize Javascript, HTML, JQuery, and CSS to dynamically set a variable based on a HTML Select's OnChange event, perform calculations, and automatically update the result?

I'm in the process of creating a pool pump calculator. While my HTML onchange function is working perfectly, I am struggling with passing the active Div value into my Javascript If Else statement and updating the outputs accordingly for each case of E ...

`Is it possible to retrieve Wikipedia information directly from a Wikipedia link?`

Is there a way to create a feature where users can input a Wikipedia page link and retrieve all the text from that page? I am working on adding a functionality to my website where users can paste a link to a Wikipedia page they want to analyze into an inp ...

AJAX: How to handle a successful POST request?

I have been recently exploring AJAX and I can see why I hesitated to delve into this particular area of JavaScript; it appears quite intricate. Most discussions seem centered around how to SEND data via POST, with little focus on what happens once the POS ...

Creating a JavaScript class that mimics the behavior of a C# class/object and can be seamlessly used in a Vue component

I am looking to develop a unique Javascript class that can be instantiated from a Vue component and have functions called on it similar to how it is done in C#. public class MyCustomClass() { public MyCustomClass(string someParameter){ .... ...

Moving a div on key press can be accomplished using a combination of HTML, CSS

I am currently working on an HTML game where the player can navigate around the webpage. However, I am encountering issues with getting the movement functionality to work. My goal is to have the player move when certain keys are pressed. While I was able t ...

Accessing the currently operating WS server instance with NodeJS

After successfully setting up a basic REST API using NodeJS, ExpressJS, and routing-controllers, I also managed to configure a WebSocket server alongside the REST API by implementing WS. const app = express(); app.use(bodyParser.json({limit: "50mb"})); a ...

Building a Search Object using Template String Types

Here is a type definition that allows for specific responses: type Response = 'n_a' | 'n_o' | 'yes' | 'no' I want to create a type that ensures underscores are replaced with slashes: type ReplaceUnderscoreWithSlash& ...

Signature index that allows for distinct types for accessing and setting values

At the moment, it is feasible to have a setter that supports both undefined/null and a getter for non-undefined/non-null values: export interface IProperty<T> { get value(): T; set value(value: T | undefined); } // the following is ok with & ...