Retrieve the availability status of an element as a boolean value with the help of Protractor

I am attempting to use an 'If' condition to determine the presence status of an element, but I'm having trouble getting a simple 'true' or 'false' result. Instead, I get an error message like this when the element is not found:

  • Failed: No element found using locator: By(css selector, .alert-message.ng-binding.alert.alert-success)

Here is the code I've implemented:

describe("test 1", function () {
    it("testing", function () {
        var userCreationSuccessConfirmationMsg = element(by.className('alert-message ng-binding alert alert-success'));
        var userCreationFailureConfirmationMsg = element(by.className('alert-message ng-binding alert alert-danger'));

        browser.driver.get(testData.UBETURL);
        login.loginToUbet('sysadmin', 'password');
        console.log('Somesh');
        element(by.linkText('Configuration')).click();
        element(by.linkText('Create New User')).click();
        element.all(by.id('saveUser')).first().click();
        console.log(expect(userCreationSuccessConfirmationMsg.isDisplayed()));
        userCreationSuccessConfirmationMsg.isDisplayed().then(function (status) {
            if (status) {
                console.log(status);
            } else {
                console.lgo(status);
            }
        });
    });
});

Can anyone provide guidance on how to obtain the availability status of an element in Boolean using 'if' conditions?

Answer №1

To check if an element is present on a page, you can utilize the isPresent method:

userCreationSuccessConfirmationMsg.isPresent().then(function (status) {
    if (status) {
        console.log('Element is present');
    } else {
        console.log('Element is not present');
    }
});

You can find more information about this in the documentation:

http://www.protractortest.org/#/api?view=ElementFinder.prototype.isPresent

Answer №2

Understanding success as the returned status being 'true' allows for a simple check against the expected string:

confirmationMessage.isDisplayed().then(function (success) {
    if (success === 'true') {
        ...
    }
});

Answer №3

Here's a suggestion for you: consider skipping logging altogether if everything is working smoothly:

expect(userCreationSuccessConfirmationMsg.isDisplayed()).toBeTruthy('Custom message to show on expectation failure.')

Jasmine allows for optional messages with expectations, and most matchers support this feature.

You may also want to check out my custom library - it handles element visibility intelligently by waiting for the element before failing the expectation. This can be handy when dealing with elements that appear after a delay. Feel free to send any feature requests!

Learn more about my library here

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

Server-side Socket.io connection is not functioning

Below is a snippet from my app.js: var app = express(); var server = app.listen(3000);//http.createServer(app);//app.listen(3000); var io = require('socket.io').listen(server); io.sockets.on('connection', function (socket) { conso ...

What is the process for converting a typescript file into javascript using programming methods?

I'm currently exploring methods to convert a TypeScript file into a JavaScript file programmatically. Is it feasible to achieve this using ts-node as shown below: function tsMiddleware (req, res, next) { var parsed = require('url').par ...

The .value property on the form group displays numeric values as either null or an empty string

I'm encountering an issue with extracting data from a form group. Within my code, there is a formGroup named lineitemForm, and I am attempting to structure this form group as follows: private formatTransferData() { const depositDates = this.get ...

Opening a window in ExtJS when another window is already open

It seems like I'm having trouble opening a new window on top of another window that is already open in ExtJS 6. I have tried setting the model to true and bringToFront to true, but unfortunately, neither of them is working as expected. https://i.sstat ...

Erase jQuery from the text

I am struggling with splitting or removing text from a filename. For example, if I have filenames like: 200726100_50-0002.JPG 230514008_60-0001.JPG The desired result should be: 230514008_60.JPG 200726100_50.JPG Am I not using the split function cor ...

Executing Node.js with npm

Is there a way to configure node to run with a specific memory size, such as below: node --max_old_space_size=4096 I also need to execute the following npm command along with it: npm run build:aot:prod Any suggestions on how I can achieve this dual exe ...

Is there a way to position the angular loading bar inside a specific 'div' instead of at the top of the page?

Recently, I integrated angular-loading-bar.js into my project to visually represent the progress of http calls. By default, the blue progress bar appears at the top of the screen. However, I wanted to customize it so that it would appear within a specific ...

What is the proper way to correctly position a radio button on a webpage?

http://jsfiddle.net/BD8j2/ I am attempting to position a radio button next to an arrow image, but it seems to be relocating elsewhere inexplicably. My intention is to have the radio button positioned between the arrow and the word "Masculino." The radio ...

Issues with Firefox's rendering of HTML are causing display problems

The image above highlights an issue I am experiencing with my website. A small black line is protruding from behind my dropdown menu, and in Firefox the word resources appears below home. However, in IE and Chrome, the menu looks fine except for the small ...

When using Node-React, it consistently responds with a status code of 500 instead of

I'm facing issues with error handling on my server. While testing on localhost, everything runs smoothly and custom errors are returned correctly to the client. However, after deploying to a host like Heroku or Render, valid requests work as expected ...

Guide to utilizing JavaScript for a basic gaming experience

Looking to incorporate multiple divs that will vanish upon being clicked, while also increasing the score by 1 through javascript. Any suggestions on how to accomplish this? ...

Is it possible to search for a value within an array of objects in MongoDB, where the value may be found in any object within that array?

Here is the schema: {"_id":"_vz1jtdsip", "participants":{ "blue":["finettix"] "red":["EQm"] }, "win":"red"," __v":0} I have multiple documents l ...

Issues with AJAX functionality in ASP .Net MVC

I'm struggling with implementing AJAX and jQuery in a partial view. The issue I'm facing is described below: In my view MyAction.cshtml, I receive a collection of StudentViewModel objects: @model IEnumerable<MvcApplication4.ViewModels.Studen ...

Has a newly created element been styled or are all values set to default since it is outside of the DOM?

First, I begin by creating an element: let link = document.createElement('a'); After my document is fully loaded and all styles and scripts are applied. The styles may look something like this: a { background-color: salmon; } Therefore, it w ...

Div containing elements positioned side by side

<div class="card-body" data-bind="if :showParam() || editParameters() "> <form class="col-lg-12 col-md-12 col-sm-12 form-horizontal" data-bind="submit: submitReportData"> <div id="input-holder" data-bind ...

Modify the animation for displaying material-ui dialog

Is it feasible to customize the display animation of a dialog in material-ui for react by using CSS? My understanding of CSS is limited, but I've heard about concepts like transitions and transforms that may be helpful in accomplishing this. ...

The Angular single-page application ensures that the navigation bar continues to highlight the corresponding section based on the current URL

In my Angular SPA application, the main routing navigation highlights the correct heading. Now, I need it to highlight as active when a specific link is clicked that contains a "5" in the URL. For example, if the URL is: http://srpdop03/doc-home/#/coordi ...

What is the best hogan.js templating option to pair with express.js?

The template package called hogan.js that is provided by express is known as hjs. However, the last update to this package was made a year ago, and there are open issues in the GitHub repository from around the same time (although they are not particularly ...

Set the default radio selection to be checked when it is assigned an object as the ng-value

Within my controller, I have a scoped object that initializes default values for my app as shown below: //set default values for form $scope.appText = { 'size':'normal', 'colour':'green', 'alignme ...

Unable to display logout option without refreshing the page after successfully logging in using AngularJS

Upon logging in successfully, users are reporting that the logout button is not visible in the header section. However, upon refreshing the page, the button becomes visible and allows them to remove cookies. How can this be resolved without the need for a ...