Protractor issue: Out of bounds error encountered when attempting to use a function for the second time

I encountered an issue with a function that selects a category from a list of available categories. The function worked perfectly in my initial test, but when I used it with a different valid category name for another test, it failed and displayed the following error message:

Error: Index out of bound. Trying to access element at index: 0, but there are only 0 elements that match locator By.cssSelector(".grid-view-builder__category")

this.categoryElements = element.all(by.css('.grid-view-builder__category'));

this.selectCategory = function (categoryName) {

    var filteredCategories = this.categoryElements.filter(function (category) {
        return category.getText().then(function (text) {
            log.info(text);
            return text === categoryName;
        })
    })

    filteredCategories.first().click().then(function () {
        log.info("Select Category: " + categoryName);
    }).then(null, function (err) {
        log.error("Category: " + categoryName + " Not Found !!" + err);
    });

}

Spec File

var columnSelect = require('pages/grid/columns/columnselector-page')()

it('Add Publisher ID Column to the Grid & Verify', function () {

    var columnCountBefore = columnSelect.getColumnCount();

    columnSelect.openColumnSelector();
    columnSelect.selectCategory('Advanced');
    columnSelect.selectColumn('Publisher ID');
    columnSelect.apply();

    var columnCountAfter = columnSelect.getColumnCount();

    expect(columnCountAfter).toBeGreaterThan(columnCountBefore);

});

Answer №1

One potential issue may lie in how you are defining and using Page Objects. Here is a suggestion to address this - if this resolves the issue, we can delve into why it occurred.

Transform the categoryElements into a function instead of just a property:

this.getCategoryElements = function () {
    return element.all(by.css('.grid-view-builder__category'));
};

this.selectCategory = function (categoryName) {

    var filteredCategories = this.getCategoryElements().filter(function (category) {
        return category.getText().then(function (text) {
            log.info(text);
            return text === categoryName;
        })
    })

    filteredCategories.first().click().then(function () {
        log.info("Selected Category: " + categoryName);
    }).then(null, function (err) {
        log.error("Category: " + categoryName + " Not Found !!" + err);
    });

}

Alternatively, the root cause could be related to timing - consider incorporating an Explicit Wait using browser.wait() to ensure at least one category is present:

var EC = protractor.ExpectedConditions;
var category = element(by.css('.grid-view-builder__category'));

browser.wait(EC.presenceOf(category), 5000);

Answer №2

Seems like the issue is unrelated to the code provided above, but rather that the CSS selector being utilized isn't locating any elements.

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

Angular testing error: Parameter 'fn' is expected to be a function but received an Object instead

I am facing an issue while trying to set up the unit test for my directive, which has its own controller. Even though adding the controllerAs property to the directive is considered a best practice, I still encounter the same error even after implementing ...

Dynamic routes in NextJS automatically append a .txt extension to the end of the URL

Issue: When using NextJS, the link <Link href="/link">link</Link> redirects to /link.txt For a simple link like this, HTML <a href="/link">link</a> can be used instead The real problem arises when using NextJS ...

JSON input in react.js sadly ended abruptly

I am encountering a problem when I attempt to submit the form. Unhandled Rejection (SyntaxError): Unexpected end of JSON input Whenever I press the submit button, this error occurs, here is the code snippet: onButtonSubmit = () => { this.setState({ ...

Exploring protractor and webdriver basics in the context of a non-angular application

Currently, I am in the process of writing end-to-end tests for a non-angular application using Protractor. While there is a wealth of information available on how to achieve this, it appears that there are multiple approaches to consider. This has led me ...

What are some ways to maintain consistent audio levels on a jquery volume slider?

My html5 webpage features a slider and an audio track, but I am not using the sound tag property controls="controls". I want the slider to control the volume of the audio file. When I include the following code in the body tags, everything works perfectly: ...

Incorporate parameters and data attributes with ScriptInjector in GWT

Is there a way to pass the id=someScript and param1=value1 to ScriptInjector in GWT? For example, consider the following JS code: <script src="https://blah.com/someScript.js" id="someScript" param1="value1"></script> In GWT, you can load it l ...

prompting users in a node.js application

I need help with querying the user multiple times in my Node.js application. Currently, all responses get printed out together and the first response is processed by both functions. I suspect this issue arises from the asynchronous nature of Node.js. Can s ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

When resetting the function, make sure to move the class to the closest sibling element

I am currently utilizing a slider that employs the .prev and .next jQuery functions to toggle the active class, indicating which slide is being displayed. Here is the code responsible for this functionality. It identifies the current sibling with the acti ...

Retrieve information from a deep array structure

How can I extract the `id` from each marker's `routes` array in this JavaScript object while still referencing `item.id`? { "markers": [ { "id": "77475", "smsCode": "77475", "name": "Abbey Sports Centre" ...

Sorting elements in an array using jQuery is a common task that can be easily accomplished

Query: I am faced with a challenge in handling a table where rows are dynamically added upon button clicks. To allow users to rearrange the rows, I have incorporated the jquery-ui sortable() function for sorting purposes. Consider the following scenario: ...

What is the best way to retrieve chosen "CheckBoxes" from a tree view with JavaScript?

I am currently working with the asp TreeView control and I am interested in obtaining the selected values of "checkboxes" on the client side. Is there a way for me to retrieve the selected values from the TreeView? ...

Unexpected outcomes arising from using nested arrays with jQuery validation plugin

I have been utilizing the jQuery validation plugin from . I am encountering an issue with validating a nested array "tax_percents[]" that is within another array. The validation seems to only work for the first value in the array, and even for the second f ...

elevate the div with a floating effect

My goal is to create a chat feature for users that will only be visible for a limited time period. I was thinking of using PHP and timestamp to achieve this functionality, but I also want to make the chat visually disappear by having the message div float ...

What is the best way to set the keyframes CSS value for an element to 0%?

Would like to create a progress indicator div using CSS animations? Check out the JSBin link provided. The desired behavior is to have the div width increase from 30% to 100% when the user clicks on stage3 after stage1, rather than starting from 0%. Althou ...

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...

Displaying Real-Time Values in ReactJS

Hi there, I am currently using the code below to upload images to Cloudinary: import React, { Component } from 'react'; import './App.css'; import Dropzone from 'react-dropzone'; import axios from 'axios'; const F ...

jQuery problem: Unable to access a property that is undefined

After testing my code on JSfiddle, I noticed that it works perfectly. However, when I try to implement it on a webpage with jQuery already loaded in the DOM, I encounter a console error, shown in the screenshot. I am certain that the iframe selector I am ...

Updates to the AngularJS model are not appearing in the user interface

Despite executing the controller code, the values in the UI remain unchanged. The initial values are displayed without any issue. I've attempted to call $scope.$apply() at the end of each function (submit and transfer), but it didn't resolve the ...

Ways to release a client-side script with npm?

Within my nodejs package, I have included code that can be executed on both the backend and in a single .js file for browsers. In order to utilize the browser script, it must be placed within a script element in an HTML file. My query pertains to whether t ...