In Jasmine, anticipate that an array of floating point values will be similar to another array

Testing a JavaScript function that returns an array of numbers involves checking if the returned array contains the same elements as the expected output:

expect(myArray).toEqual(expectedArray);

The comparison works well with arrays containing only integers, but when floats are present, it fails due to floating-point precision errors. Using toBeCloseTo on arrays doesn't seem to solve the issue.

Currently, I am using a loop for member-wise verification:

for (var i = 0; i < myArray.length; i++) {
    expect(myArray[i]).toBeCloseTo(expectedArray[i]);
}

However, is there a more concise way of achieving this? When the test fails, it generates an excessive number of error messages in the output.

Answer №1

Here is the code snippet that provides a solution to your query:

function testIfArraysAreClose(actualArray, expectedArray) {
  expect(actualArray.length).toBe(expectedArray.length)
  actualArray.forEach((element, index) =>
    expect(element).withContext(`[${index}]`).toBeCloseTo(expectedArray[index])
  )
}

Answer №2

Give this a shot:

for (let index=0; index<arrayReturned.length; index++){
  if(arrayExpected.indexOf(arrayReturned[index]) === -1 ){
      console.log("No match found")
      break;
  }else{
      console.log("Match found!")
      break;
  }
}

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 AJAX POST form consistently submits data from the initial entry in the list

Upon investigation, I have discovered that the issue is linked to my AJAX posting method. When I submit the form using the standard method (action=""), it successfully populates my database based on the selected record from the list. However, when I util ...

Error occurs when implementing Google login in React, happening both during rendering and after successful sign-in

Hey there! I recently started using React-Google-Login to implement a sign-in button on my project. I followed the documentation closely, but unfortunately ran into 2 errors while testing it out. Here's the code snippet I currently have: import Goog ...

Dynamic resizing of grids using React and TypeScript

I'm attempting to create a dynamic grid resizing functionality in React and TypeScript by adjusting the lgEditorSize value on onClick action. Setting the initial lgEditorSize value const size: any = {}; size.lgEditorSize = 6; Adjusting the lgEditorS ...

BreezeJS model, Knockout integration, empty relationships

I am facing an issue where, when using breeze manager.saveChanges(), only the navigation properties are not sent to the server. The rest of the data is being transferred properly. I am relatively new to Breezejs and hoping someone experienced can assist me ...

Extract a subset of an array based on the specified pairs of indices in r

After extensive searching, I still haven't found a clear answer to my question. Let's say I have the following array: vector1 <- c(5,9,3) vector2 <- c(10,11,12,13,14,15) result <- array(c(vector1,vector2),dim = c(3,3,2)) My goal no ...

How to Extract C-style Arrays from NSArray Objects

I've got an NSArray called arr, filled with NSNumber objects. My goal is to perform statistical analysis on this array using GNU's GSL, which requires C-style arrays as parameters. Is there a way to apply the 'intValue' function to all ...

JQuery for Seamless Zoom Functionality

I am working with some divs that have images as backgrounds, and I have added a zooming effect on hover. However, the zoom effect is not smooth. Is there a way to modify the script to make the zoom effect smoother? Here is an example of my HTML structure: ...

Object contains a key within another object

I have an array of objects, each containing another object. I want to check if a specific key exists within the inner objects. var myarr = [{ hello: "world", payload: { kekek: 'sdfsdfsdf', baby: 'sdfsdfsdfds&apo ...

Should I release an Aurelia component on NPM?

Our team has developed a compact Aurelia application and now we are looking to seamlessly incorporate it into a larger codebase. One possible scenario is distributing the Aurelia app on NPM to allow other projects to easily integrate our code. What steps ...

I am attempting to draw a correlation between two numerical variables

I'm struggling to compare two scores in my game. When they match, I want it to display "You won", but I can't get it to work. I've attempted using the parseInt method and .val method, but no luck so far. var numberFour = Math.floor(Math.ra ...

Unexpected behavior: Bootstrap modal triggers twice upon closing and reopening

When I click a button, a login form modal is displayed. This modal is loaded from an external file using AJAX. However, I have encountered an issue where if I close and reopen the modal, it launches twice and the modal-backdrop class appears twice as well. ...

What is the procedure for generating a mouse event for clicking a tab in Selenium WebDriver?

As I work with Selenium WebDriver and Java, there is a tab named PR Per Product. Under the PR Reports tab, there are multiple tabs. In the PR tab, I used: WebElement menuHoverLink = driver.findElement(By.id("ext-pr")); actions.moveToElement(menuHoverLink) ...

Retrieving JSON data from an API

As a beginner with Jquery JSON and API's, I am trying to work on hitting an API that returns city names in JSON format. I need to display these city names dynamically on my webpage in a list format. Can someone guide me through this process? If you w ...

"In Laravel, there seems to be an issue with looping through a 2-dimensional

I have a snippet of code that I'm trying to loop through twice on an array as shown below: $rules = Rule::get(); $segments = []; foreach ($rules as $rule) { $segments['segment = "basic"']['serv ...

There was an error of "Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor"

I've been diving into cannon.js and encountering the following error: Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor. I've tried numerous solutions but none seem to be working. Here's a snippet of my script: var scene, came ...

Top method for handling chained ajax requests with jQuery

I'm facing a scenario where I have to make 5 ajax calls. The second call should only be made once the first call returns a response, the third call after the second completes, and so on for the fourth and fifth calls. There are two approaches that I ...

Unraveling and interpreting JSON data stored within a database field

When I try to display the JSON data stored in my database directly in HTML, I notice some strange characters that seem to be encoded. Here is a snippet from the HTML file: '{&quot;web_rendition&quot;:{&quot;@xmlns&quot;:&quot;& ...

Is it secure to store information that impacts component rendering within a JWT payload?

I am currently developing a MERN app where users have various roles, and different components are rendered based on their role in React. In my application, I store a JWT containing the user's ID and role in a cookie, which is then decoded in a global ...

Populate a database with information collected from a dynamic form submission

I recently created a dynamic form where users can add multiple fields as needed. However, I'm facing a challenge when it comes to saving this data into the database. You can view a similar code snippet for my form here. <form id="addFields" me ...

Assigning values to an array can lead to unpredictable outcomes

Context: My task is to create a function that uses backtracking to compare two integer arrays. The function should return 0 if the arrays are different and 1 if they are the same. The question does not specify the size of the arrays, how they are filled, o ...