Approximating Values with JavaScript in Selenium

Hi there! I've been exploring selenium IDE and encountered an issue related to asserting an approximate value. My challenge is to validate a numeric value within an element identified by its id, where the value is in numerical format with commas separating decimals.

The task at hand requires me to verify if the numeric value falls within a tolerance of 0.01.

Let's consider an example:

<div id="uniqueId">2,54</div>

assertText - value = 2.53

In this case, I need the test to pass based on the provided example, as well as for values like 2,52 or 2,53. While I am aware that assertEval allows insertion of JavaScript code, my proficiency in JavaScript is limited. Additionally, the capabilities of selenium in terms of executing JavaScript are somewhat restricted from what I have gathered.

Any guidance or assistance on this matter would be greatly appreciated!

Answer №1

It is recommended to use assertEval for this task. The necessary javascript code will look something like this:

var numberStr = "${actualText}".replace(",", ".");
var number = parseFloat(numberStr);
var difference = Math.abs(eval(number-${expectedValue}));
(difference <= 0.01)?true:false;

While I am not very familiar with javascript, based on this discussion, it is important to first change the decimal mark from ',' to '.' (as seen in the 1st line) so that we can later convert the string extracted from the page into a number (as shown in the 2nd line).

The variable ${actualText} holds the actual value retrieved from the page, whereas ${expectedValue} is a user-defined value. Keep in mind that the tolerance level (0.01) is currently hardcoded and could be replaced by a variable.

To condense the code (at the expense of readability):

(Math.abs(eval(parseFloat("${actualText}".replace(",", "."))-${expectedValue}))<=0.01)?true:false

With the javascript code ready, we can then create the Selenium script:

storeText  | id=uniqueId                   | actualText
store      | 2.53                          | expectedValue
assertEval | INSERT JS CODE HERE            | true

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

Building an interactive array with checkboxes and mapping in React JS: A step-by-step guide

I am currently working on mapping a list of formations and would like to implement a dynamic array that updates when a checkbox is selected in the onChange event. The goal is to keep my organization updated with the formations they are able to dispense. ...

What might be causing the issue of a click handler not registering during the initial page load when using Enquire.js

I am experimenting with different effects on various breakpoints. My main goal is to achieve the following behavior: when a category is clicked from the list within 720px, the category list should fade out while the data is revealed in its place. However, ...

Employing the new operator in conjunction with a variable

Is there a way to achieve the following scenario: var foo = function(){ this.value = 1; } var bar = "foo"; var baz = new bar(); alert(baz.value) // 1 Specifically, I am looking for a method to instantiate an object using its string name. Any sugge ...

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

Generating various arrays of data

I am currently facing an issue with creating separate datasets based on the month value. Despite my efforts, all month values are being combined into a single dataset in my code. Any assistance in dynamically generating different datasets would be greatly ...

Uncovering the Mystery Behind the Repetitive Execution of useEffect in Next.js

I am working on a Time Tracking feature for my Next.js application. In the ./app/components/TimeTracking.tsx file, I have implemented the following component: 'use client'; import React, { useEffect, useState } from 'react'; import { u ...

How to effectively leverage useMediaQuery in material ui?

Upon completing the web application, I have made the decision to ensure it is mobile-friendly. Utilizing the material UI framework with react, I delved into the documentation but found myself uncertain about how to effectively implement it. Let me provide ...

Using Node.js, Handlebars, and Express for template inheritance

As I embark on my Node.js learning journey, I am starting with creating simple applications to grasp the fundamentals. Recently, I wanted to implement a Django-like template structure in my projects but found myself stuck on how to achieve it. I have come ...

The .val() function in jQuery can sometimes give different results when used on input elements with placeholder text in Firefox compared to Chrome

After analyzing the given HTML code, I've noticed discrepancies in the values returned by jQuery in Firefox and Chrome: HTML: <input type="text" name="name" id="name" placeholder="Type Here"> <input type="email" name="email" id="email" plac ...

Is it possible to leverage specific client-side Javascript APIs on the server-side?

Exploring APIs designed for web browsers that require their .js code to return audio streams. In a broader sense, these APIs provide byte streams (such as audio) for playback in the browser. Is it possible to use these APIs in server-side Javascript frame ...

Using jQuery to load HTML response into entire page

When working with my ajax code, I receive a html response. Is there a way to entirely replace the current page with this html response? So far, I have only come across window.location.href, which simply redirects to the url response. Here is a snippet of ...

Failure of default option to appear in dropdown menu in Angular

I currently have a dropdown list in my HTML setup like this: <select id="universitySel" ng-model="universityValue" ng-options="university._id for university in universities"> <option value="-1">Choose university</option> ...

Learn how to dynamically insert an element into an angular scope using a click event

Currently, I am working on a function called onGroundUserClick within the Scope passedScope. The goal is to have a function triggered upon the completion of loading the iframe that will establish ng-click. var $tdName = $("<td/>", { ...

What is the reason for a button triggering a complete reload of my webpage?

I am currently working on a web page using jQuery and experiencing inconsistent behavior with certain elements. Whenever any button on the page is clicked, it causes a refresh of the page. It seems like there is code running that reloads the page whenever ...

Can a static text be displayed randomly using Javascript?

What I'm searching for is a unique text display feature that's different from scrolling. I envision a subtle fade in/out effect, but it's not necessary. The main goal is to fit within a small area on a website with limited vertical space - ...

Having trouble resolving the import org.openqa when trying to add the Selenium library to your Java or Android project? Let's walk through

I am on the lookout for effective Selenium tutorials that actually deliver results. Currently, I have been exploring this particular one, and unfortunately, the project seems to be encountering some issues with compilation. There are a total of 6 errors: ...

Recursion using Node.js Promises

I'm facing some difficulties while iterating through my Promises and completing my parser code: let startFrom = 0, totalRecords = 10000, doneRecords = 0 const rows = 10 const parserRequests = function () { if (startFrom <= totalRecords) { ...

Using Node Express.js to access variables from routes declared in separate files

Currently, I am in the process of developing a website with numerous routes. Initially, all the routes were consolidated into one file... In order to enhance clarity, I made the decision to create separate files for each route using the Router module. For ...

Position the previous and next buttons next to the thumbnail images

I've implemented the cycle2 jQuery plugin on my website successfully, but I'm facing an issue with positioning the prev and next buttons next to my thumbnails. I want them to be aligned with the first and last thumbnail without relying on absolut ...

Error in PHP script when making an AJAX call

First of all, I want to thank you all for your help. The script is creating a table but sending empty information. I have tried to modify it like this: However, when I call the script, it gives me an error: So, I have edited the script code to clean it ...