Here's a unique approach to this topic: "Utilizing fixture files in Cypress to extract an array and perform

As I am relatively new to cypress, I am encountering an issue that I could use some help with. In the fixtures folder, there is a TestData.json file that contains the following data:

{  
  "data1":  
  {   
    "Client": "Client1",  
    "ClientID": "202300001",  
    "PlanTypes": ["type1", "type2"]  
  },  
  "data2":  
  {   
    "Client": "Client2",  
    "ClientID": "202300001",  
    "PlanTypes": ["type3", "type4", "type5"]  
  }  
}  

The website I'm working on has a dropdown list with items like these:
Client Plan Types: "", "type1", "type2", "For Validation" (where "" and "For Validation" are default items while type1 and type2 are dynamic and change per client)

To tackle this, I have successfully extracted these items into an array named "arr1". However, my struggle lies in comparing arr1 with PlanTypes (from fixtures). Also, I need to dynamically add "" and "For Validation" values to PlanTypes before comparison without altering the fixture file itself.

Below is a snippet of my code:

script.js

import filePage from "../../../support/page-objects/filePage";
const filePage = new filePage()
const testDataFile = '/TestData.json'
cy.fixture(testDataFile).then((testData) => {
  const msTestData = testData.data1
  filePage.checkPlanTypes(msTestData);
});

filePage.js

checkPlanTypes(msTestData) {
let arr1 = []
this.elements.dataPlanTypeList().find('li').each((planTypeData) => {
  arr1.push(planTypeData.text().trim())
}).then(() => {
  let clientPlanTypes = []
  clientPlanTypes.push("")
  clientPlanTypes.push(msTestData) 
  clientPlanTypes.push("For Validation")

  expect(clientPlanTypes).to.have.same.members(arr1)
})
}

Upon running the code, an error message appears stating "expected [ Array(4) ] to have the same members as [ Array(3) ]".

I also attempted "

cy.wrap(arr1).should('deep.equal', clientPlanTypes)
", but it resulted in another error: "expected [ Array(4) ] to deeply equal [ Array(3) ]"

When I cy.log(clientPlanTypes), the output is "[, [REGULAR, VIP], For Validation]"

If you have any insights or suggestions on how to effectively compare PlanTypes (clientPlanTypes) and arr1, your assistance would be greatly appreciated. Thank you!

Answer №1

Adding an array to another array will result in a nested array structure:

["", ["type1", "type2"], "For Validation"]
let clientPlanTypes = []
clientPlanTypes.push("")
clientPlanTypes.push(msTestData) 
clientPlanTypes.push("For Validation")

To flatten the array, you can utilize the flat method

let clientPlanTypes = []
clientPlanTypes.push("")
clientPlanTypes.push(msTestData) 
clientPlanTypes.push("For Validation")

clientPlanTypes = clientPlanTypes.flat()    // un-nests the array

This will give you:

["", "type1", "type2", "For Validation"]

Answer №2

It seems like the issue arises from the code where you are appending the data from the fixture to the new array:

clientPlanTypes.push(msTestData) 

By doing this, you are inserting an array (msTestData) into the new array (clientPlanTypes) instead of adding the elements of the fixture array individually. This explains why your cy.log output shows

[, [REGULAR, VIP], For Validation]
instead of the expected
["", REGULAR, VIP, For Validation]

You can rectify this by looping through the fixture array and appending each element separately.

clientPlanTypes.push("");
msTestData.forEach((value) => {
  clientPlanTypes.push(value);
});
clientPlanTypes.push("For Validation");

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

Disable button not necessary when validating checkboxes

I'm working on a simple function that involves 3 checkboxes. The goal is to disable the button if all checkboxes are unchecked, and enable it only when all three checkboxes are checked. function checkAll() { var checkbox1 = document.getElem ...

Does vanilla Javascript have a similar function to Jquery's Require function?

I'm currently using the require function in RequireJS, but I'd like to achieve something similar in vanilla JavaScript. How can I go about doing this? require(['underscore', 'jquery', 'settings', 'text!/core/use ...

Encountering an undefined response in API call using Fetch with Express Nuxt

I've hit a roadblock with a task involving Express, API, and Fetch. I'm utilizing Nuxt along with Shopify API endpoints to retrieve data such as orders. Below is my express API Endpoint which should return an array of objects (orders). const bod ...

What are the key conditions for aligning two arrays of strings?

I have a query that requires some logical thinking. I am looking to display a string in the format "[email protected] [email protected]" for each user whose job title and manager match the job title, department, and manager in the group ...

Adding Currency Symbol to Tooltip Data in Material-UI Sparklinechart

Below is a SparklineChart example using MUI library: import * as React from 'react'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import { SparkLineChart } from '@mui/x-charts/SparkLineCha ...

Using Javascript to toggle visibility of radio buttons on a PDF form

I've been looking around but haven't come across any information regarding using JavaScript with PDF form applications. If I missed something, I apologize and would appreciate any guidance. Currently, I have 5 radio buttons that are synchronized ...

Different Ways to Modify the Appearance of Angular's mat-slide-toggle and mat-checkbox

I am facing an issue in my Angular form where I have a select box containing objects derived from database records. The goal is to automatically populate the form with the object values once one is selected. My Angular application includes an array of obj ...

Exploring Netbeans 7.3 for Enhanced JavaScript Autocomplete with Parameters

Ever since the upgrade to netbeans 7.3, I've encountered an issue where netbeans no longer automatically provides me with parameter names. For instance, When I see "methodA(param1, param2) xxx.js" in the autocomplete pop-up, clicking on it or pressi ...

Using jQuery to pass dynamic values to a plugin function

I'm currently utilizing the JSONTable plugin and attempting to dynamically pass values to the 'head' and 'json' parameters by extracting them from an array object. For instance, I aim to load a new json file, convert it to a JavaSc ...

Issue with rendering JavaScript in Django template

I encountered an issue with my template that includes JavaScript. For example: <script>var i = /{{([a-z]*)}}/gi;</script> Typically, the template interpreter tries to interpret anything inside double curly braces {{}} as a variable. I am now ...

What is the process for triggering a function event on click (or any other function) within a browser's activation?

Some time ago, I was trying to figure out why the onclick event wasn't working when I clicked on a specific area of the browser. After consulting a guide, I discovered the issue and fixed it. It turns out that the problem was quite simple, and now I u ...

Button from Material-UI vanishes upon being clicked

I encountered an issue with a button that disappears when clicked on. Additionally, clicking the button once does not trigger any actions associated with it. In order to execute the button actions, I have to click the area where the button was located afte ...

what is the process for installing non-NPM libraries with browserify?

My current project involves working with Angular and using Bower as the package manager. However, I now want to integrate some npm modules in the browser by using Browserify. Initially, I was able to npm install angular angular-ui-router --save for my sta ...

Implementing automatic value setting for Material UI slider - a complete guide

I am working on developing a slider that can automatically update its displayed value at regular intervals. Similar to the playback timeline feature found on platforms like Spotify, Soundcloud, or YouTube. However, I still want the slider to be interactive ...

Warning: The Unhandled Promise Rejection arises when an error is thrown within an asynchronous function without a try-catch block

Encountering the following issue in my Node-Express App UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error came about either by throwing inside an async function without a catch block, or rejecting a promise that was not hand ...

What is the reason behind using <script> tag for scripts, instead of using <style> tag for external CSS files?

A family member who is new to Web Development posed an interesting question to me. Why do we use <script src="min.js"></script> and <link rel="stylesheet" href="min.css">? Why not simply use <style href="min.css"></style>? Wh ...

Generating a random number to be input into the angular 2 form group index can be done by following these

One interesting feature of my form is the dynamic input field where users can easily add more fields by simply clicking on a button. These input fields are then linked to the template using ngFor, as shown below: *ngFor="let data of getTasks(myFormdata); ...

Implement a feature in React that allows for the copying of values from one input field to another when a

Within my form, I have implemented two address field groups - one for shipping and another for billing. I am looking to enhance user experience by providing them with the option to copy values from the shipping address group to the billing address group wh ...

Chrome experiencing stuttering issue with jQuery's .slideUp() function

When I click a button, I want to hide certain elements in my HTML document. $(document).on('mouseup','#button',function() { setTimeout(setupBox1,100); setTimeout(setupBox2,Math.floor((Math.random() * 3000) + 800)); setTimeo ...

Creating a distinct numerical identifier and maintaining a tally in Java: What's the best approach?

Currently, I am coding a Java robot that extracts data from an excel file and uses it to create a unique username in another program. The only piece of information missing from the excel file is an ID number. To remedy this, I am attempting to create a 6- ...