How does Jasmine compare to the second parameter with the toBeCloseTo function?

Jasmine's documentation is often brief, but not always sufficient.

I am curious about the second parameter of the toBeCloseTo function. The official reference only provides this example:


it("The 'toBeCloseTo' matcher is for precision math comparison", function() {
    var pi = 3.1415926, e = 2.78;
    expect(pi).not.toBeCloseTo(e, 2);
    expect(pi).toBeCloseTo(e, 0);
});

While it mentions "precision," what does that mean practically in this context? Is it related to the number of digits after the decimal point that must match?

In my scenario, I need to compare two timestamps in milliseconds and consider them close if the difference is less than 100.

For instance, what value should X be in this case?


var timestamp1 = 1501254807000;
var timestamp2 = 1501254807099;
var timestamp3 = 1501254807100;
var precision = X;
expect(timestamp1).toBeCloseTo(timestamp2, precision); //this assertion should pass
expect(timestamp1).toBeCloseTo(timestamp3, precision); //this assertion should NOT pass

If the precision only deals with decimals, I could convert the integers to decimal numbers by dividing them by 1000. However, I'm unsure about the value of X. As of now, I'm using the following approach:

 
expect(Math.abs(timestamp2-timestamp1)).toBeLessThan(100);

Although functional, it lacks readability compared to using toBeCloseTo (which I prefer to use if possible).

Thank you.


Edit. The outcomes below might provide some clarity:


expect(1000000.005).toBeCloseTo(1000000.000,3); // this fails
expect(1000000.005).toBeCloseTo(1000000.000,2); // this fails
expect(1000000.005).toBeCloseTo(1000000.000,1); // this passes

Answer №1

According to @Nikolaj, the "precision" parameter determines the number of decimal places used for precision checking in the matcher.

In the scenarios you provided, the first two comparisons fail because they differ at 3 and 2 decimal places respectively (the trailing 05 gets rounded to 1 at 2 decimal places). However, they match at 1 decimal place.

The matcher can handle negative precision values, like:

expect(1000).toBeCloseTo(1003,-1); //pass
expect(1000).toBeCloseTo(1100,-2); //fail
expect(1000).toBeCloseTo(1100,-3); //pass

But it's not very flexible beyond that. Unfortunately, this means the matcher may not be suitable for your needs, so you may have to stick with your original solution.

Answer №2

One specific scenario I found in the Jest documentation really shed light on the importance of using the toBeCloseTo matcher.

When we write expect(0.1+0.2).toBe(0.3); it fails because the result is 0.30000000000000004
However, when we use expect(0.1+0.2).toBeCloseTo(0.3); it passes successfully.

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

Is there a way to simulate AWS Service Comprehend using Sinon and aws-sdk-mock?

As a newcomer to Typescript mocking, I am trying to figure out how to properly mock AWS.Comprehend in my unit tests. Below is the code snippet where I am utilizing the AWS Service Comprehend. const comprehend = new AWS.Comprehend(); export const handler ...

Having trouble using angular.isString in conjunction with ng-repeat

Is there a way to use angular.isString for comparison within an ng-if in an ng-repeat loop? Currently, all items in the array are being returned. I attempted to simply display the result of angular.isString, but no output is generated. This is my desired ...

The Jquery .remove() function will only take effect after the second click

I am currently working on implementing a notifications feature using bootstrap popover. The issue I am facing is that after a user clicks on a notification, it should be removed. However, for some reason, it requires two clicks to actually remove the notif ...

Using JQuery to load a table and inject it with html()

I am looking to populate an HTML table within a specific div element. The HTML code is being loaded using the following jQuery function: $("#table_wrapper").hide(); $.get("<?echo base_url();?>schichtplan/employee_fields/"+plan_id+"true",function(da ...

Handling multiple render calls and rerenders in React function components with setTimeout (best practice for firing multiple times)

Is there a way to optimize the Notification component in my App, so that the setTimeout function is only initialized once even if multiple notifications are pushed into the state? function Notification(props) { console.log("Notification function compone ...

Unfortunately, my capabilities do not allow me to execute the command 'ng build --configuration production

This is the issue that I am facing and need assistance: Error: src/app/app.component.html:1:1 - error NG8001: 'fuse-progress-bar' is not recognized as a valid element: If 'fuse-progress-bar' is an Angular component, please ensure that ...

JavaScript providing inaccurate height measurement for an element

Upon loading the page, I am trying to store the height of an element. To achieve this, I have utilized the jQuery "ready" function to establish a callback: var h_top; var h_what; var h_nav; $(".people").ready(function() { h_top = $(".to ...

What is the best way to update a specific section of my website by modifying the URL while keeping the menus fixed and the site functioning smoothly?

I am in desperate need of assistance as I search for a solution. Currently, I am working on a project involving music within a web browser or application. My goal is to utilize HTML, PHP, JS, and CSS to create this project. If I start with a website, I p ...

The onCreated listener function in the jBox Modal dialog is experiencing issues and not functioning properly after the first use

I am using jBox from the URL: . Every time I click on a link, a modal is created. The first time the modal is created, listeners for the buttons on that modal are properly added in the "onCreated" attribute and work when clicked. However, from the second ...

The process of converting a data:image base64 to a blob is demonstrated in this code snippet

Seeking a way to convert data:image base64 URLs to blob URLs. Below is the original code that generates the base64 URLs: <script> $(window).load(function(){ function readURL() { var $input = $(this); var $newinput = $(this ...

Table Header Stays Put Without Shrinking or Expanding with Window Adjustment

I have a sticky table header that stays at the top when scrolling down on my web page. To achieve this effect, I followed the solution provided on css-tricks.com/persistent-headers/. However, I encountered an issue where the sticky table header does not ...

displaying a pair of distinct elements using React techniques

I need help adding a react sticky header to my stepper component. When I try to render both components together, I encounter an error. To troubleshoot, I decided to render them separately. Surprisingly, when rendering separately, I do not get the "store is ...

How to dynamically load bootstrap-multiselect within a loop in a vueJs application

I am attempting to dynamically load bootstrap-multiselect in a loop using VueJs. My desired implementation looks something like this: <div class="col-xs-6 col-sm-4 mb-1" v-for="params in param"> <select class="mult" multiple="multiple"> ...

Does Three.js come with a default function for generating heightmaps?

Currently, I am engrossed in developing a JavaScript game using Three.js. My interest lies in enhancing the realism of the walls by incorporating a height map (refer to the provided image). View this snapshot of the game design featuring a 2D wall. All th ...

iOS 10.3.1 causing Ionic 2 (click) event to trigger twice

I am currently working on an Ionic 2 app and I am facing an issue with the click event. When I test the app on a device and click on a button, let's say to trigger an alert, the function executes once. However, if I click on the button again, the fun ...

Organize divs based on their attributes

Using inspiration from this SO post, my goal is to group divs based on their "message-id" attribute. The idea is to wrap all divs with the same "message-id" in a div with the class name "group". <div class="message" message-id="1"> ...

Unable to alter the protocol option of the request object in SailsJS

Currently, I am utilizing a library that relies on the req.secure option to proceed without any errors. However, my application is deployed on Heroku and I have implemented custom middleware to check the "x-forwarded-proto" header and set req.secure as tru ...

Display a dropdown menu when hovering over with a delay

I recently created a basic navigation menu with dropdown functionality using CSS3 initially, but I decided to enhance it by incorporating jQuery to display the dropdown after a set timeframe. However, I am facing an issue where all dropdowns appear when ho ...

Navigating through nested arrays to access JSON objects

My attempts to retrieve the JSON data from this particular API have been unsuccessful. Every time I try to fetch the JSON, I am faced with a specific set of results as shown in the code below. const request = require('request'); var url = ' ...

How to create dynamic transition effects in modal using AngularJS

My modal includes a next button for easy navigation. Initially, the modal showcases content within: <div ng-show="step1"></div> Upon clicking the next button, the modal transitions to display different contents in 'step2' within th ...