Personalized Jasmine matchers for a Protractor/WebDriverJS component

Greetings fellow developers,

I'm looking to create a custom matcher for Protractor/WebDriverJS element. Can anyone assist in improving my current code?

Here is what I aim to include in the specs files:

var button = element(by.tagName('button'))
expect(button).toBeEnabled();

Here's my customized Jasmine matcher:

'use strict';

function improvedMatcher(util, customEqualityTesters) {
  return {
    compare : function (actual, expected) {
      var result = {};

      expect(actual.isEnabled()).toBeTruthy()

      result.pass = true;

      if (result.pass) {
        result.message = 'Expected element to be disabled';
      }
      else {
        result.message = 'Expected element to be enabled';
      }

      return result;
    }
  };
}

module.exports = improvedMatcher;

Is there a more efficient way to write this? Currently, if there is an error, I receive the message: Expected false to be true. However, I would prefer to see "Expected element to be enabled."

Appreciate your assistance.

Answer №1

From my understanding, Jasmine custom matchers are essentially objects that contain matchers as keys within them. Therefore, when calling a custom matcher, you must use the object key associated with it. In your code, you have hard-coded the value result.pass = true;, which prevents the else block from executing in case of a failure. As a result, the statement 'Expected element to be enabled.' will never be displayed. To rectify this issue, consider the following revised implementation:

'use strict';

var customMatchers = {
    toBeEnabled: function (util, customEqualityTesters) {
        return {
            compare : function (actual, expected) {
            var result = {};

            result.pass = actual.isEnabled();

            if (result.pass) {
                result.message = 'Expected element to be enabled';
            }
            else {
                result.message = 'Expected element to be disabled';
            }

              return result;
            }
        };
    }
}

Here is an example of how you can utilize this custom matcher:

var button = element(by.tagName('button'))
expect(button).toBeEnabled();

I hope this explanation proves helpful.

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

The animation speed of the jQuery hashchange event is set to zero, causing the animation

I'm facing an issue with jQuery where my animation inside a hashchange event is not smooth; it happens instantly when triggered. I'm looking for a way to make the animation smoother. jQuery( document ).ready(function() { jQuery(window).on(&a ...

Encountering an issue when trying to download a PDF from an Angular 6 frontend using a Spring Boot API - receiving an error related to

When I directly call the Spring Boot API in the browser, it successfully creates and downloads a PDF report. However, when I try to make the same GET request from Angular 6, I encounter the following error: Here is the code snippet for the Spring Boot (Ja ...

Building a single-page app optimized for mobile viewing with Foundation framework

Currently facing an issue with the scaling of the viewport on certain mobile devices when loading new content via ng-include in our responsive website built on Foundation. The problem arises as the width of the page breaks, leading to horizontal scrolling. ...

What causes the Error: ENOENT open error to occur when attempting to render a doT.js view?

My first experience with doT.js led me to create a basic server setup: 'use strict'; var express = require('express'); var app = express(); var doT = require('express-dot'); var pub = __dirname+'/public'; var vws ...

Invoking Ajax Within Every Loop

I am creating dynamic HTML buttons where, upon pressing each button, I want to make an AJAX call to retrieve a value. However, I am encountering an issue where I get as many console outputs as the number of buttons pressed. Here is my PHP code: if(isset($ ...

Creating fresh texts by pairing the values in constants with variables

Make sure to carefully read the question before proceeding. I have attempted multiple commands in order to retrieve a single variable from the server [TSE](https://old.tsetmc.com/Loader.aspx?ParTree=15131F) which serves Stock Exchange information. The pag ...

Techniques for utilizing ng-class to merge class attributes

I'm new to Angular and I want to combine classes using ng-class. Specifically, I'd like to use the save class along with the firstClass class if something = First. I've been doing some research on how to implement this with ng-class but I ha ...

Tips on identifying HTML email input validation using JavaScript?

Just like when you can determine whether an input element with a required attribute was successfully validated, try using the following code: if($('input[type="email"]').val() && $('input[type="email"]').val().includes('@') & ...

"Why does the useEffect in Next.js fire each time I navigate to a new route

Currently, I have implemented a useEffect function within the Layout component. This function is responsible for fetching my userData and storing it in the redux-store. However, I have noticed that this function gets triggered every time there is a route c ...

Tips for generating various series using dx-Chartjs

Trying to visualize ratings based on their type is proving to be difficult as I can't seem to figure out how to group the series according to types. The available chart options are: $scope.chartOptions = { dataSource: data, c ...

Adding dots between page numbers when using ReactJS/Javascript Pagination can be achieved by implementing a specific method

I have created a pagination component using React JS. Currently, it only displays all the page numbers, but I want it to show dots when there are more than 8 total pages. Here's how I envision it: c. When total is less than 9 pages: Page 1 selecte ...

Obtaining the value of a checkbox with React

I have a form with two input fields (email, password) and a checkbox. The code for the form is shown below: <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}> <TextField margin="normal" required ...

What is the process for retrieving values from tags, such as text, contained within another tag? Specifically, how can you access the value of an h1 tag that is inside a p tag?

Currently, I am using Selenium with Python to tackle a specific issue. My goal is to extract information from within a paragraph (p tag). To achieve this, I utilize the "find_elements_by_tag_name" method to locate all the p tags on the page. However, my ch ...

Snapshots in AngularJS SEO with PhantomJS can be created either before or during the crawling process

What is the best approach for generating snapshots (snapshots being a plain HTML version of an Angular state/route created for SEO purposes)? Should it be done every time an author adds a post in a blog? Or should it be generated during crawling? Link t ...

Node.js and TestCafe encountered a critical error: Inefficient mark-compacts were performed near the heap limit, resulting in an allocation failure. The JavaScript heap ran

While executing my test scripts in Node v14.6.0, I encountered the following problem. Here are some of the options I've tried: I attempted to increase the Node Heap Size but unfortunately had no success: export NODE_OPTIONS=--max_old_space_size=4096 ...

The baffling quirks of variables within a Jquery loop

Unfortunately, I'm struggling to come up with a more fitting title for my question, but I'll do my best to provide a clear explanation of my issue. Here is the code snippet I am working with: let pdfInvoice_sub_template = [ {text: '{ ...

Inject the content loaded from the server into a div element, and insert that div at the

I am trying to insert the div(#loadmore) element inside the div(#boxchatting) element when the content from "result.php" is loaded into div(#boxchatting). Here is the code I used: $('#loadmore').prependTo('#boxchatting'); $('#boxc ...

Looking to bring in a non-ES6 library into VueJS without using export statements

Currently, I am faced with an interesting challenge. For a forthcoming VueJS project, we must utilize a library that is quite outdated but there is simply not enough time to redevelop it. The library is essentially a JavaScript file which consists of num ...

Include chosen select option in Jquery form submission

Facing some challenges with a section of my code. Essentially, new elements are dynamically added to the page using .html() and ajax response. You can see an example of the added elements in the code. Since the elements were inserted into the page using . ...

Direct your attention to the div element using ng-click

I'm encountering a complex issue while developing an AngularJS input helper component for number fields in my web application. To better explain the problem, let me give you some background on how our components function: Each component consists of i ...