Ways to validate an element in an Array using Cypress dynamically

I have a question regarding the dynamic verification of Array elements. For my project, I need to suggest a price that will increase over time, and I require a script that can verify these elements dynamically. In the screenshot provided, you can see what needs to be verified. The script I used is as follows:

    ` describe('POST method', () => {
    it('suggest a price', () => {
     //Suggest a price you are willing to pay. Available only for auctionType: fixed_price

        cy.request({
            method: 'POST',
            url:"xxxxxx",

            headers:{
                "Authorization":"LOOL",
                "content-type": "application/json"
            },

            body: {
                "id": "d42f516a867590633dd8a82cb2563437",
                "bid": 6900,
                "auctionPlatformId": "xxx",
                "auctionPlatformUserId": 0
            },

            failOnStatusCode: false

            
        })


expect(res.status).to.eq(200)
      expect(res.body).to.have.property("id", "d42f516a867590633dd8a82cb2563437")
      expect(res.body).to.have.property("amount", 6900)
      expect(res.body).to.have.property("auctionPlatformId", "abc")
     expect(res.body).to.have.property("auctionPlatformId", 0)`

However, this code lacks dynamism and does not perform the required verifications.

https://i.sstatic.net/aoSiQ.png

Answer №1

Using the within method and defining a range is one approach.

expect(res.body.amount).to.be.within(6000,7000)

To generate random bid values, you can utilize Math.random

"bid": Math.floor( Math.random() * 10000 ) + 1  //Generate random numbers between 1 and 10000

If all amounts in the response are expected to be less than or equal to the input bid amount, you can implement the following strategy. Define minimum and maximum values for the random bid amount and then assert that the response body's numbers fall within this range.

describe("POST method", () => {
  it("suggest a price", () => {
    //Suggest a price you are willing to pay. Available only for auctionType: fixed_price
    var minval = 1
    var maxval = 10000
    var bidAmount = Math.floor(Math.random() * maxval) + minval
    cy.request({
      method: "POST",
      url: "xxxxxx",

      headers: {
        Authorization: "LOOL",
        "content-type": "application/json",
      },

      body: {
        id: "d42f516a867590633dd8a82cb2563437",
        bid: bidAmount,
        auctionPlatformId: "xxx",
        auctionPlatformUserId: 0,
      },

      failOnStatusCode: false,
    }).then((res) => {
      expect(res.status).to.eq(200)
      //Assert individually if needed
      expect(res.body.suggestedPrices[0].amount).to.be.within(minval, maxval)
      expect(res.body.suggestedPrices[1].amount).to.be.within(minval, maxval)
      expect(res.body.suggestedPrices[2].amount).to.be.within(minval, maxval)

      //Assert all together in a loop
      for (var index in res.body.suggestedPrices) {
        expect(res.body.suggestedPrices[index].amount).to.be.within(
          minval,
          maxval
        )
      }
    })
  })
})

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 it possible to invoke a helper function in Node.js from within a callback?

I recently started programming with node.js and I am encountering an error that I can't quite figure out. The function appears to be correctly set up, and I don't believe there are any asynchronous issues because of the self variable I have in pl ...

What is the solution to prevent the div tag from being empty within Jquery UI Tabs?

I found this example that I am currently following: http://jqueryui.com/demos/tabs/#ajax After clicking on Tab1 and Tab2 in their example, the text disappears immediately, and the div box shrinks before new data is loaded. Is there a better way to handle ...

When working with React.js, encountering the error message "Unexpected token export on export{default as

When attempting to import components into my newly installed app, I used the following syntax: import {Cards , Chart , CountryPicker} from '../components' I also created an index.js file with the following content: export {default as Cards} ...

When a promise is executed, it runs the code synchronously regardless of the promise

Essentially, I have a web application that fetches data from Firebase. Due to the time it takes to retrieve this data, I've implemented promises in JavaScript to ensure my code executes at the appropriate times. Within the function getDataFirebase, in ...

Iterating over a range of values with _.each()

Can someone help me figure out why my syntax is incorrect for applying two values from different iteratees (day.classes and event.part) on line 5? <div class="days"> <div class="headers"> <% _.each(daysOfTheWeek, function(day) { %&g ...

What steps should I take to ensure that the proper link is loaded and opened when the loop is clicked?

I've been working on a script to display the top 25 posts from reddit and have their respective links open in a sliding div below. However, I'm running into an issue where the script outputs the same post for every item in the loop. I understand ...

Persisting a single module using vuex-persistedstate

Is there a way to configure vuex-persistedstate so that only one module persists state through page refresh? Currently, when I use plugins: [createPersistedState()] inside the user module, it does not work. plugins: [createPersistedState()] only works wh ...

IE11 experiences frequent crashes when running a web application utilizing the Kendo framework and JavaScript

I am experiencing difficulties with my ASP.NET MVC application that utilizes Kendo UI and jQuery. Specifically, when using Internet Explorer 11, the browser crashes after a short period of usage. The crash does not seem to be linked to any specific areas o ...

Create a token for

Visit this link for more information on listing functions in Azure web apps https://i.sstatic.net/YgsF5.png Is there a way to dynamically generate the green-highlighted token using JavaScript or an API? While I'm aware that the token can be generate ...

JavaScript animation not functioning properly when height is set to "auto"

Can someone help me figure out why setting the height to "auto" in the code snippet below isn't working as expected? I want the DIV to adjust its size based on the content, but it's not happening. Any ideas on how to fix this issue would be great ...

Using props in the v-bind:src directive with Vue - a comprehensive guide!

I have a Vue application with a Block component that needs to display an image. The Block component is used multiple times in the App component, each time passing a value to determine which image src to choose from an array. When I try to print {{ this.Im ...

Guide to seamlessly integrating form data into MySQL using JavaScript and HTML without redirecting the user from the current page

Having trouble inserting a new user into MySQL database? I've attempted using both jQuery and pure JavaScript, but it doesn't seem to be working. There's no response when I click on the submit button. Any ideas on what might be causing this ...

Guide on showing the content of an uploaded file as an object in JavaScript using file reader

When using the file upload function to upload a json file and read its contents, I am encountering an issue where the result is in string format instead of object. How can I display it as an object? Here is my code: .html <div class="form-group"> ...

Starting with React.js in Rails 5

I'm currently diving into the world of integrating react.js into my Rails 5 application. After adding the react-rails gem to my project, I utilized the generator to create my initial component with the command: rails generate react:component AppRole ...

Leveraging ThemeProvider Parameters with Global Styled-Components

When working with styled-components, how can I access the props of the ThemeProvider in the context of global.js? For instance, in my theme.js file, I have ${props => props.theme.fonts.fontSize} set to a default font size of 16px. const theme = { ...

Unable to locate the required conditional template for the 'mdRadioButton' directive due to the absence of the 'mdRadioGroup' controller

I am currently working on developing a custom directive that will help me display questions within a survey. Given the multiple types of questions I have, I decided to create a single directive and dynamically change its template based on the type of quest ...

Issue encountered during JSON file extraction (Firefox)

Within my Node.js application, there is a specific route where I retrieve a large JSON dataset from a Postgres database and then send it in a compressed format as a response. To accomplish this, I utilize the Zlib module to compress the data using gzip. Be ...

Error: Unable to access the 'comments' property of a null value

Encountering an issue when trying to add comments to a post, resulting in the error message: TypeError: Cannot read property 'comments' of null Post routes: router.post("/", async (req, res) => { console.log(req.params); Post.findById(r ...

Unexpected provider error in AngularJS when using basic module dependencies

I am encountering an issue with my module setup involving core, util, and test. The util module has no dependencies and one provider The test module depends on util and core, and has one controller The core module depends on util, and has a provider that ...

Using Javascript to Implement Pinch Zoom on Android

After searching through the depths of the internet, I have yet to come across a viable solution or answer. The challenge at hand is the need to implement pinch zoom functionality for an element (specifically an image) using JavaScript in a Phonegap environ ...