After successfully navigating past the login page on my website using JavaScript, my Selenium driver suddenly ceases to function

My current automation test involves logging into a hotel booking website using Selenium and Cucumber. After successfully logging in, I attempt to click on a checkbox labeled "wifi", but encounter issues with Selenium not functioning properly once logged in.

I am able to enter the username and password on the login page without any problems, but for some reason Selenium stops working after the login process, preventing me from clicking on the wifi button. I have tried using implicit wait, but this does not resolve the issue.

Below is the code snippet:

 
const {By, Key, Builder} = require("selenium-webdriver");
require("chromedriver");

const {Before, Given, When, And, Then} = require('@cucumber/cucumber')

let driver = new Builder().forBrowser("chrome").build();

var {setDefaultTimeout} = require('@cucumber/cucumber');
setDefaultTimeout(60 * 1000);

Given('when you are on the login page', async function () {
   
    await driver.get("https://automationintesting.online/#/admin")

});

When('you enter login credentials', function () {

     driver.findElement(By.id("username")).sendKeys("admin");
     driver.findElement(By.id("password")).sendKeys("password");
     driver.findElement(By.id("doLogin")).click();
});

When('you are logged in', async () => {
  
    await driver.manage().setTimeouts({ implicit: 3000 });
    await driver.findElement(By.id("wifiCheckbox")).click();
});

Then('you should be on the profile page', function () {
  
    driver.getCurrentUrl();
});

The section of code that functions correctly is as follows:


driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("doLogin")).click(); 

However, the portion of code below is where the issue arises:

 
driver.manage().setTimeouts({ implicit: 3000 });
await driver.findElement(By.id("wifiCheckbox")).click();

I AM ENCOUNTERING A REQUEST FAILED 403 ERROR MESSAGE

Answer №1

The 403 error code in the Request Failed indicates that the server has received the request but refuses to authorize it.

const { By, Key, Builder } = require("selenium-webdriver");
require("chromedriver");

const { Before, Given, When, And, Then } = require('@cucumber/cucumber');

let driver = new Builder().forBrowser("chrome").build();
const { setDefaultTimeout } = require('@cucumber/cucumber');
setDefaultTimeout(60 * 1000);

Given('when you are on the login page', async function () {
  await driver.get("https://automationintesting.online/#/admin");
});

When('you enter login credentials', async function () {
  await driver.findElement(By.id("username")).sendKeys("admin");
  await driver.findElement(By.id("password")).sendKeys("password");
  await driver.findElement(By.id("doLogin")).click();
});

When('you are logged in', async function () {
  const wifiCheckbox = await driver.findElement(By.id("wifiCheckbox"));
  await driver.wait(until.elementIsVisible(wifiCheckbox), 10000, 'Wi-Fi checkbox not found');
  await wifiCheckbox.click();
});

Then('you should be on the profile page', async function () {
  const currentUrl = await driver.getCurrentUrl();
  // Further validations or assertions can be added here
});

Make sure to import all necessary packages before running the code

Answer №2

When it comes to programming, Java and JavaScript have distinct behaviors. Java operates synchronously, executing tasks in a sequential manner, while JavaScript is inherently asynchronous, allowing for simultaneous task handling, making it ideal for dynamic websites.

For functions like sendKeys, click, setTimeouts, and getCurrentUrl that return a Promise, it is essential to use the async and await keywords. Additionally, utilizing a combination of implicit wait and explicit wait becomes necessary for cases where elements load slowly or shift during page navigation.

const { By, Key, Builder } = require("selenium-webdriver");
require("chromedriver");

const { Before, Given, When, And, Then } = require("@cucumber/cucumber");

let driver = new Builder().forBrowser("chrome").build();

var { setDefaultTimeout } = require("@cucumber/cucumber");
setDefaultTimeout(60 * 1000);

Given("when you are on the login page", async function () {
  await driver.get("https://automationintesting.online/#/admin");
});

When("you enter login credentials", async function () {
  await driver.findElement(By.id("username")).sendKeys("admin");

  await driver.findElement(By.id("password")).sendKeys("password");

  await driver.findElement(By.id("doLogin")).click();
});

When("you are logged in", async () => {
  await driver.manage().setTimeouts({ implicit: 3000 });

  const wifiCheckbox = await driver.wait(
    until.elementIsVisible(
      await driver.findElement(By.id("wifiCheckbox")),
      10000,
      "Wi-Fi checkbox not found"
    )
  );
  await wifiCheckbox.click();
});

Then("you should be on the profile page", async function () {
  await driver.getCurrentUrl();
});

Because of JavaScript's asynchronous nature, these adjustments are crucial for ensuring responsiveness and improved speed in web interactions.

Please take note of the typo in "credentials" and the extra space at the end of the "you are logged in" step name, as correcting these details is important for smooth execution in your feature file.

Answer №3

Adjust the implicit timeout setting before attempting to locate the elements.

Follow this example:

Before('attempting login', async function () {
  await browser.manage().setTimeouts({ implicit: 15000 });

  await browser.findElement(By.id("usernameInput")).sendKeys('exampleUser');

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

Issue with event listener not functioning properly with dynamically created content using AJAX (only using vanilla JavaScript

I used pure javascript AJAX to dynamically load content into the "test" div. However, when I try to click on a child div at index 6, an alert box is not being displayed as expected. How can I fix the issue with the click event not working? The gets functi ...

Exploring numerical elements in interactive content

Struggling with the Wikipedia API and encountering issues with the results that are returned. {"query":{ "pages":{ "48636":{ "pageid":48636, Concerned about how to access a specific ID (such as 48636) without knowing it in advance ...

What is the best method for selecting only files (excluding folders) in Gulp?

I have a gulpfile where I am injecting files into an appcache manifest in this manner: var cachedFiles = gulp.src('**', {read: false, cwd: 'build'}); gulp.src('src/*.appcache', {base: 'src'}) .pipe($.inject(cachedF ...

"Creating a dynamic Vue array using computed property from the provided dataset

Let's consider a scenario where data is retrieved from a store: let itemsData=[ {id:1,data:[...]}, {id:2,data:[...]}, {id:3,data:[...]} ] The goal here is to create another array, itemsSelected, that looks like this: let itemsSelected=[ {id:1 ...

Manipulate the value of the <input> element when focused through JavaScript

After I focus on the input field, I was expecting to see Bond-Patterson, but instead, I am only getting Bond. What could be causing this discrepancy and how can it be fixed? $('input[name="surname"]').attr("onfocus", "this.placeholder='Bo ...

I am encountering a problem with my Vuex getter where it is sending an Array with a length of 0, but when expanded in the console,

Currently, I'm utilizing Vuex to interact with a Django API in order to fetch count data. state: { DailyCycleDate: [] }, getters: { DailyCycleDate : state => { console.log('Getter') console.log('Length of Array: &apo ...

A code snippet designed to ensure uniform height for all floating div elements

Hello, I am facing an issue with resizing 20 left-floated divs of varying heights on my website. Previously, when my website was designed using pixels, a script worked perfectly for resizing them. However, after switching to a percentage-based design (% d ...

Guide on utilizing map function in JavaScript and Vue to generate a fresh array

I am working on implementing a map method in JavaScript and Vue to generate a new array of objects while only including specific items in each object. I have designed a user interface with 2 checkboxes corresponding to 2 distinct objects: <div v-for ...

The display and concealment of a div will shift positions based on the sequence in which its associated buttons are clicked

I am in need of assistance with coding (I am still learning, so please excuse any syntax errors). What I am trying to achieve is having two buttons (button A and button B) that can toggle the visibility of their respective divs (div A and div B), which sh ...

Tips for sending attributes to jQuery autocomplete

I'm facing a major issue with implementing a jquery autocomplete feature, and JavaScript isn't my strong suit. Currently, I'm using the jquery.auto-complete plugin available at: https://github.com/Pixabay/jQuery-autoComplete, which is an up ...

What is the reason for my result showing as Object { } rather than MyObj { }?

When utilizing the web development tools console, if a browser object is typed, it will return as "console." > console Console { } > console.log(console) undefined > Console { } This behavior applies to all browser objects. However, when I try ...

Enhance your viewing experience by magnifying a specific element, all while maintaining full control to navigate

Is it possible to create a zoom effect on a webpage that focuses on one specific element while still allowing for navigation and scrolling? I have searched online for plugins like Fancybox and Zoomooz, but none of them offer the functionality I need. I sp ...

Display the first item last in an *ngFor loop in Nativescript Angular

I'm facing some confusion with the sorting of an array in JavaScript. Although the index, last, and first seem to be correct, the result is not as expected. Versions @angular/core: 4.1.0 nativescript-angular: 3.1.3 typescript: 2.4.0 Expected 1234 ...

Upon a successful AJAX post request, the page fails to display

I'm encountering an issue connecting my front-end JavaScript to my back-end Node/Express. Although the requests from my client-side js to the server return successful, the page I am requesting fails to render. On the server side, here is my code: ap ...

Facing a challenge in configuring MongoDB automatic data expiration based on specific time zones

I am currently facing an issue with clearing data in MongoDB at the start of each day. For example, on July 15, 2020 at 00:00:00, data is deleted from the database based on a specific time. I am having trouble properly assigning the expiresAt attribute in ...

Enabling and disabling multiple input fields based on the status of a checkbox in order to manage dynamic inputs

I need help with a situation involving dynamic input fields and checkboxes. My goal is to disable the input field if the checkbox with the corresponding ID is checked. Here is the PHP code snippet: <table class="table table-striped"> <thead& ...

What is the process of branching a stream with highland.js?

I have a stream called sourceStream that contains objects of type BaseData. My goal is to split this stream into n different streams, each filtering and transforming the BaseData objects according to their specific criteria. Ultimately, I want to end up ...

The collection is not an array

I am currently running the following code: var n = []; jQuery.toJSON( n ); Interestingly, on one page I receive "[]", while on another I get ""[]"". Both pages are utilizing the same version of jQuery along with a toJson Plugin. Upon inspecting the arra ...

Whenever a timeout or "element not clickable" issue arises, my cucumber feature step consistently comes to a halt

Every time my cucumber feature step encounters a time out or element not clickable issue, it abruptly stops running. When I run my automation script with multiple feature files, the cucumber feature step always halts when it encounters the aforementioned ...

methods for transferring JSON data from JavaScript to PHP

I am trying to figure out how to parse JSON data from JavaScript to PHP. Here is my JavaScript code: var Dataconvert; var asetid = new Array(); $("#simpanmodifikasi").click(function(){ var table = $('#tableasal tbody' ...