What steps can be taken to ensure a protractor test fails when a function does not succeed

For debugging my protractor test cases, I have developed helper methods. One of the key functions is waiting for an element to be clickable. To ensure that Protractor has enough time to find and enable the element, I am implementing a loop. However, in case the element is not located due to a typo or other issues in the script, I want the test run to immediately STOP and mark it as a FAILURE.

 async WaitToBeClickable(element){
       try{
           for(var i = 0; i <= 3000; i++){
               var wait = await browser.wait(this.EC.elementToBeClickable(element), i);
               if(wait == true){
                   break;
               }else{
                   //this is where I want to fail
               }
           }
       }catch(err){
           //this is where I want to fail
           await console.log(`WAIT TO BE CLICKABLE FAILED:\n${element.parentElementArrayFinder.locator_.value}\n\nError:\n${err}\n`);
       }
   };

This feature aids greatly in debugging my scripts while working on VSC. However, I am struggling to figure out how to make the test FAIL and close the browser upon the first failure. The options like protractor-fail-fast and protractor-bail-fast seem to cater to Jasmine test cases rather than individual functions. Any assistance would be highly appreciated as Protractor is making me a bit frustrated at the moment!

Answer №1

//function

const validateData = () => {
     return new Promise((resolve) => {
           if(true){
               // Passed scenario
               return resolve(true)
           }
           else{
               // Failed scenario
               return reject(false)
           }
  })
}


//Test file

it('example test', async () => {
    let result = await validateData();
    expect(result).toEqual(true);
})

The test outcome is based on the resolved value

Answer №2

If your code encounters an error, you can utilize the done function provided by Jasmine.

For example:

it('should perform a specific action', async done => {

    try {
        await performAction();
    } catch (e) {
        done.fail(e); // mark the test as failed
    }

    done(); // mark the test as completed
}, 1 * 60 * 1000);

async function performAction() {
    throw Error('the action failed');
}

Answer №3

Have you considered simply rethrowing the error in the catch block? This should trigger a test failure.

Feedback:

You don't need to await a console.log since it's a synchronous operation. Additionally, browser.wait will throw exceptions if the element isn't found within the specified timeout. It seems like your for loop may not be necessary here.

This function waits 3000ms for the element to become clickable. If the element doesn't become clickable within that time frame, an exception is thrown and caught in the catch block. The error message is logged before rethrowing the error, ultimately causing your test to fail (unless the error is handled elsewhere).

async WaitToBeClickable(element){
  try {
    await browser.wait(this.EC.elementToBeClickable(element), 3000);

  } catch (err) {
    console.log(`WAIT TO BE CLICKABLE FAILED:\n${element.parentElementArrayFinder.locator_.value}\n\nError:\n${err}\n`);
    throw new Error(err);
  }
};

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

Having trouble with tabs in jQuery?

I'm having trouble setting up tabs in a reservation form with 3 tabs that include text boxes for user input. I can't seem to get it working properly and I'm not sure where I've gone wrong. Could it be due to the placement of the content ...

Using importXML with Internet Explorer 11

My project website includes a roster page that retrieves XML data. Previously, this functionality worked across all browsers but now it only works in Chrome. In IE11, it seems that the importXML function is not functioning correctly as the roster data is m ...

Ways to Ensure a Property of an Object Remains Synced with Another

I'm dealing with the following Object structure: { a: "123" b: "$a" } In this setup, b should always be equal to the value of a. Any suggestions on how I can achieve this using JavaScript? ...

What's the Deal with React-Admin's Uninformative Class Names?

I am in search of clarity on a rather fundamental query concerning react. Is it common to come across the following class names within react-admin based web applications? class="jss136 jss138 jss125 jss127" Currently, I am involved in a project that inv ...

A method of binding data from an array of objects in Vue using v-bind

I am tasked with rendering a board that is 20x15 and placing creatures on it. The information on where to place the creatures is stored in this.creaturesOnBoard within the gameEngine. My plan is to take X and y coordinates, then check if a creature exists ...

Use JavaScript or jQuery to calculate the total value of selected radio buttons and display it in the corresponding textbox

I'm looking to calculate the sum of values from radio buttons and display that sum in the corresponding textbox using either JavaScript or jQuery. Each radio button should have a unique class name for its results. So far, I've only managed to ...

"An error has occurred stating that the function Factory.function() in AngularJS

I'm a beginner with AngularJS and could use some assistance! My issue involves retrieving JSON data from a URL in a factory function and returning it to the controller. However, I keep getting an error stating that the function doesn't exist. Wh ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...

How to deselect a radio button in AngularJS

I have explored various solutions using ng-dblclick, $event, etc, but none of them seem to work for me. Within a table, I have two radio buttons inside an ng-repeat. I have a field that determines which radio button should be active. While using ng-change ...

Unable to choose an item from an unordered list with Selenium in Python

To choose an item from a list in an unordered way utilizing selenium python is my present task. HTML: <div class="ms-drop bottom" style="display: block;"> <ul style="max-height: 400px;"> <li class="ms-select-all"> ...

$filter is functioning correctly, however it is generating an error message stating: "Error: 10 $digest() iterations reached. Aborting!"

Here is an example of a JSON object that I am working with: { "conversations":[ { "_id": "55f1595d72b67ea90d008", "topic_id": 30, "topic": "First Conversation", "admin": "<a href="/cdn-cgi/l/e ...

Capture the item selected from the dropdown using ng-model to retrieve the name instead of the

I need help getting the name/text/html of the selected option in a dropdown using angular.js, rather than just its value. Currently, I have this setup which retrieves the value: Here is my HTML code snippet <select class="SelectCar" ng-model="Selected ...

Issues encountered while trying to access a child state using Ionic and UI-Router

My current setup includes the following parent states: // Abstract state for tabs directive .state('tab', { url: "/tab", abstract: true, templateUrl: "templates/tabs.html", controller: "TabCtrl" }) // Each tab has its ow ...

How can the ID of a table row be retrieved if it is selected?

In my datatable, I have a list of Cars where each row contains a Car ID. A checkbox column has been added to the first cell in the table - when checked, the row is highlighted to show the user their selection. The goal is to retrieve the IDs of all selecte ...

Selenium WebDriver can be used to choose a checkbox by selecting

Hello, I am facing an issue where I need to select checkboxes that have the same IDs. Below is the HTML code snippet: <label class="table-checkbox-label" for="record-12034"> <input id="record-12034" class="table-checkbox" type="checkbox"/> < ...

Gathering user information through Javascript to dynamically populate an HTML document

Looking to utilize JavaScript to extract the value entered in a search bar and then display it in HTML. function pullValue() { var search = document.getElementById("search-bar") } How can the extracted data be inserted into the following: <h3 class ...

Using multer to transfer variables to next handler

Utilizing multer for image uploads involves a specific configuration. Here is an example of how to set up multer: import multer from "multer"; import * as mime from "mime-types"; import path from "path"; export const storage = multer.diskStorage({ dest ...

Jest does not support util.promisify(setTimeout) functionality

While I understand there may be similar questions on SO, I believe mine is unique and hasn't been addressed in the current answers. I'm currently experimenting with testing a REST API in Express.JS. Below, you'll find a basic working exampl ...

What is the best way to perform unit testing on an Angular component that utilizes the Router?

While working in Angular 2.0.0, I encountered an issue when unit testing a component that utilizes Router. The error 'Supplied parameters do not match any signature of call target.' keeps appearing, with Visual Studio Code highlighting the new Ro ...

Leveraging Components within Components in Vue 2

Here is the code snippet I am working with: import './menu-item'; import ItemImage from "./item-image"; Vue.component('quest-card', { props: { title: String, isFree: Boolean, points: Number, ...