Stale reference to element detected in Protractor despite implementation of conditional wait

I am encountering an issue within the beforeEach function of my test class. Sometimes, clicking on the usersTab works fine, but other times it results in a StaleElementReferenceException. I have experimented with using protractor.ExpectedConditions such as presenceOf, visibilityOf, and elementToBeClickable, but none of them have provided a 100% solution. It seems that the problem may be related to asynchronous behavior where the browser attempts to click before waiting. Is this a possibility? Can anyone suggest how to handle this situation?

var OnePage = require('../pages/one_page.js');
var SecondPage = require('../pages/second_page.js');

describe('Test', function () {

    var onePage;
    var secondPage;
    var EC = protractor.ExpectedConditions;

    beforeEach(function () {
        browser.ignoreSynchronization = true;
        onePage = new OnePage();
        browser.wait(EC.presenceOf(onaPage.userLogin), 5000);

        onePage.setUser('login@login');
        onePage.setPassword('password');
        onePage.login();


        secondPage = new SecondPage();
        browser.wait(EC.visibilityOf(secondPage.usersTab), 10000);
        usersPage.usersTab.click();
    });

I am utilizing jasmine:2 and protractor:2.2.0.

Answer №1

When I first began constructing my Test Suite, I encountered a similar issue that proved to be quite challenging to resolve. It took me some time to track down a suitable solution. The problem arose from initializing the Page Object using a standard var within the beforeEach function. This led to the retention of an old instance when executing the 2nd or subsequent tests. The occurrence of this issue seemed random to me, with no clear trigger or timeline. The workaround I discovered was to leverage the this keyword within the beforeEach function, as illustrated below. This ensured that a fresh instance was created for each test.


NOTE: In my conf.js file, within the onPrepare section, I have implemented the following function to inform Protractor whether the upcoming page is Angular-based:

global.isAngularSite = function(flag) {
    browser.ignoreSynchronization = !flag;
};

var OnePage    = require('../pages/one_page.js');
var SecondPage = require('../pages/second_page.js');

describe('Test', function () {

    beforeEach(function () {
        isAngularSite(true);

        this.onePage    = new OnePage();
        this.secondPage = new SecondPage();
        this.ec         = protractor.ExpectedConditions;

        browser.wait(this.ec.presenceOf(this.onePage.userLogin), 5000);
        
        this.onePage.setUser('login@login');
        this.onePage.setPassword('password');
        this.onePage.login();

        browser.wait(this.ec.visibilityOf(this.secondPage.usersTab), 10000);
        usersPage.usersTab.click();
    });

    it('', function() {

    });

});

Answer №2

When working with multiple actions in your code, it's important to ensure they execute sequentially once the first one is completed resolving its promise. Here's a simple way to achieve this:

beforeEach(function () {
    browser.ignoreSynchronization = true;

    // Actions for OnePage
    onePage = new OnePage();
    browser.wait(EC.presenceOf(onaPage.userLogin), 5000).then(function(){
        onePage.setUser('login@login');
        onePage.setPassword('password');
        onePage.login();
        
        // Actions for SecondPage chained after the first one
        secondPage = new SecondPage();
        browser.wait(EC.visibilityOf(usersPage.usersTab), 10000).then(function(){
            usersPage.usersTab.click().then(function(){
                // If verification is needed after click, do it here.
                browser.sleep(500);
            });
        });
    });
});

To ensure that the actions on the second page are done only after those on the first page have completed, you can chain them together in the following manner:

browser.wait(EC.presenceOf(onaPage.userLogin), 5000).then(function(){
    // Actions for OnePage
}).then(function(){
    // Actions for SecondPage
    secondPage = new SecondPage();
    browser.wait(EC.visibilityOf(usersPage.usersTab), 10000).then(function(){
        usersPage.usersTab.click().then(function(){
            // If verification is needed after click, do it here.
            browser.sleep(500);
        });
    });
});

I hope this explanation helps clarify the process for executing sequential actions in your code.

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

Is there a way to implement a @click event on a Vuetify expansion panel?

Whenever I use <a>, the design of the <v-btn> expansion panel breaks. How can I incorporate the click event in this situation? I attempted to utilize filters, watch, and computed, but it didn't work. Here's my code: <v-card xs1 ...

Despite being invoked five times and enclosed in a React.Fragment tag, the functional component is still not displaying any content

<html lang="en"> <head> <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js& ...

The response header does not contain a valid JWT token

Here's a function I've implemented to authenticate users by creating a response header: function verifyUser(res, id) { const payload = { id } const token = jwt.sign(payload, config.JWT_KEY, { expiresIn: '24h' ...

What factors contribute to a one-hour discrepancy between two time stamps, deviating from the anticipated value?

Let's consider the dates '2022-04-01' and '2022-05-15'. When I calculated their deviation using Chrome devtools, here are the results: https://i.stack.imgur.com/tSZvk.png The calculated result is 3801600000. However, when my frie ...

Entity Framework and the GET request error: Connection Reset

Currently, I am working on developing a straightforward notes application using Entity Framework in ASP.Net Core for the backend and AngularJS for the frontend. The main objective is to have the app load a pre-existing list of notes from my MySQL database ...

Having trouble accessing the text in a paragraph using JavaScript executor and web driver

On a particular website, there is: <p id="tempid" value="Manual Effect">testing the test</p> String value = (String)((JavascriptExecutor) this).executeScript("return window.document.getElementById('tempid').value"); System.out.pr ...

Is the Router.refresh() function failing to refresh within the next 13 seconds?

'use client'; import { useRouter } from "next/navigation"; export default function Todo({ todo }) { const router = useRouter(); return ( <> <li key={todo.id}> <input type=&apo ...

Having trouble retrieving data passed between functions

One of my Vue components looks like this: import '../forms/form.js' import '../forms/errors.js' export default{ data(){ return{ form: new NewForm({ email: '&apos ...

Encountering an issue with DateTimeField being undefined in a React.js application

I encountered an issue stating that DateTimeField is not defined while attempting to create a date picker in react + bootstrap. I referred to the following URLs for assistance: https://github.com/Eonasdan/bootstrap-datetimepicker Link to my code s ...

Tips for modifying an HTML element's attribute when a button is clicked, both in the client and server side

Context: This question delves into the fundamental concepts of AJAX. I have been studying this tutorial along with this example for the JavaScript part, and this resource (the last one on the page) for the PHP segment. Imagine a scenario where a JavaScri ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

A guide on instantly updating displayed flat/section list elements in React Native

I am in the process of creating a screen called ContactListScreen. The direct child of ContactListScreen is ContactItems, which is a sectionList responsible for rendering each individual ContactItem. However, I have encountered a problem where my ContactIt ...

The method for transforming all headers into permalinks with jquery/javascript

I am looking for a way to transform all headers on a page into clickable permalinks using jQuery or JavaScript. Here is the HTML code: $('h3').each(function() { var id = $(this).attr('id'); if (id) { //Check if the element has a ...

What could be the reason for the counter not being incremented when the button is clicked

While attempting to increase the counter in my test, I encountered an issue where pressing the button did not change the value. I tried using both fireEvent from React testing library and React test utils, but the value remained at 10. My project is using ...

Leveraging the boolean values of attributes within JSX statements

I have been working on a React.js project where I am trying to incorporate a data-picker plugin that requires a specific style of input-attributes: <input data-enable-time=true /> However, I have encountered an issue where webpack fails to compile t ...

Is there a way to manipulate a button's toggle state using Javascript as the page loads?

I am in the process of developing a straightforward web application that allows users to customize their settings. On the settings page, there are several toggle buttons that need to have their state changed during the page load to align with the preferenc ...

What could be the reason for my function failing to return true?

I have a function that can check if a script is loaded: function checkURLExistence(url){ $.ajax({ url: url, success: function(data){ //alert(url + ' exists'); console.log(url + ' exists'); return ...

unable to gather information from suppliers

I'm currently building a login page with nextjs and spotify js, but I've run into the following error https://i.sstatic.net/cKiM8.png Here is the code snippet that is causing the issue: import React from 'react' import { getProviders ...

The on-screen keyboard using JQuery and CSS is not working properly on an HTML redesign

UPDATE - Check out the modified version here: https://codepen.io/anon/pen/wZQjQy Here is the original for reference: https://codepen.io/anon/pen/YMRLBN (had to utilize CodePen, as simply adding a snippet here doesn't link the CSS) I essentially copie ...

Error in Express application due to uncaught SyntaxError

I am attempting to live stream data using websockets to Chartjs, however I keep encountering the following error. main.js:1 Uncaught SyntaxError: Unexpected token <https://i.sstatic.net/9OCI1.png https://i.sstatic.net/bmGeW.gif What could be causi ...