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

What is the best method to transfer an array as a parameter from an Ipython notebook to an HTML file that includes specific javascript functions?

I have a unique HTML file named "file.html" that includes a distinctive JavaScript function described below: The Unique file.html <html> <head> </head> <script> function customFunction() { perform an action using ...

Troubleshooting the problem of divs overlapping when scrolling in JavaScript

I am experiencing some issues with full screen divs that overlay each other on scroll and a background image. When scrolling back to the top in Chrome, the background shifts down slightly, and in Safari, the same issue occurs when scrolling down. I have cr ...

switching the content of an element using Javascript

I'd like to switch between two icons when clicking on .switch and apply the style of .nightTextNight to .nightText, my JavaScript code is working well everywhere except here. Is there a simpler way to achieve this? I currently have to create two clas ...

Mastering linear regression calculations using vue.js and chart.js

Take for instance, with the current dataset, I am looking to showcase a linear regression I managed to do this in Vista and now I need guidance on how to proceed with the calculation. I am not too familiar with using the formula Here is my HTML: <canva ...

Transformation of Object into Number through Function Execution in Javascript

I am currently facing an issue with my animate() function while using Three.js to generate an animation. Below is a simplified version of the code: let obj; let camera = new THREE.PerspectiveCamera(fov, asp, near, far); let scene = new THREE.Scene(); const ...

What is the best way to retrieve the nearest form data with jQuery after a child input has been modified?

I have a page with multiple forms, each containing several input checkboxes. When one of the form inputs changes, I want to gather all the parent form's data into a JSON array so that I can post it elsewhere. I'm having trouble putting the post ...

The behavior of CSS position: sticky varies depending on whether the user is scrolling up or scrolling down

I am experiencing an issue in my Vue CLI app where a component with the position: sticky CSS property is being partially hidden under the top of the browser when scrolling down, but works correctly when scrolling up. This behavior is also observed on my Ga ...

"Utilizing datatables to efficiently submit form data to the server-side

I'm curious for those who utilize the Datatables javascript plugin, is there a way to replicate this specific example using server-side data? The current example I came across has its data hardcoded directly in the HTML. ...

React JS progress circle bar is a simple and effective way to visualize

Currently, I am in the process of developing a progress circle bar that will function as a timer alongside sliders. Each slide is intended to have its own corresponding progress bar. While I have managed to create the bars individually, I am facing challe ...

Having trouble loading a React component

I've been working on breaking down modules from a monolithic React project to store them separately in my npm registry. However, I'm encountering issues with exporting and importing them correctly. Previously, I was using the following code: con ...

Tips for validating a form with the assistance of jQuery

While there are multiple answers out there for this particular question, I am specifically interested in validating an entire form with dynamic input fields sourced from a database similar to Google Forms. HTML <div class="rs_card"><spa ...

Issue with hidden event callback not functioning properly in Bootstrap 3 popover

After studying this example, I attempted to incorporate a hidden callback function. While the show callback is functioning perfectly, the hidden callback seems to be ineffective. Can someone shed light on why this issue is occurring? To showcase the probl ...

Utilizing Sequelize with Typescript for referential integrity constraints

After defining these two Sequelize models: export class Users extends Model<Users> { @HasMany(() => UserRoles) @Column({ primaryKey: true, allowNull: false, unique: true }) UserId: string; @Column({ allowNull: false, unique: tru ...

Creating a script in C# to streamline the login process on Facebook using Visual Studio and Selenium WebDriver

Hey there, I've been encountering error messages when attempting to automate the login process for Facebook. I have included a link to a screenshot displaying these errors. Any suggestions on how to resolve these issues would be greatly appreciated. ...

Utilizing a Jquery plugin for enhanced form validation with the inclusion of supplementary techniques

I am looking to integrate a jQuery plugin into my form validation process, specifically to ensure that only letters are allowed in the name section. If a user enters special characters or numbers, I want the form to display an error message. Additionally, ...

Filtering a list with Vue.js using an array of checkboxes

Currently, I am exploring ways to filter a v-for list using a checkbox model array with multiple checkboxes selected. Most examples I have come across only demonstrate filtering one checkbox at a time. In the demo here, you can see checkboxes 1-3 and a lis ...

What is the method for sending a down arrow key in Capybara?

My unique requirement involves a specialized listbox automation that would benefit from simulating a down arrow keystroke and then pressing enter. The code snippet for pressing enter looks like this: listbox_example = find(input, "listbox-example") listb ...

Is there a way to prevent users from right clicking on all links with the same class using js/jquery?

Rails 4 + JS + jquery Is there a way to disable right click on links with the same class in Rails? <% @schedule_hash.values.each do |schedule| %> <%= link_to "Cancellation policy", {:controller => 'web', :action => 'get ...

Enhance ant design modal functionality by enabling resizing capabilities

I'm experiencing an issue with the Ant Design Modal component as it does not support resizing the modal window. I'm looking for a way to enable manual resizing of the modal window once it has been opened. Is there a solution available for this fu ...

Determine the employees' salaries and display any salaries that are below 5000

Hi everyone, I'm looking for guidance on how to properly utilize the Flat or flatMap method to flatten this array of employee data. Specifically, I want to retrieve the names and salaries of employees whose salary is less than 5000. const employeeData ...