Is there a method we can use to replace fixture fields with data created during the test case to produce a dynamic payload? (Already attempted existing solution)

I am new to using Cypress and I'm wondering if there is a way to generate a dynamic payload by replacing values in a JSON file with values generated programmatically in a Cypress test. This is similar to what we do in Rest Assured by substituting %s in the JSON file.

I have tried searching online but couldn't find a solution. Some similar questions that I came across were: I want to pass a dynamic JSON body to the cypress request() function & define payload values

Below is an example of a JSON file:

{
    "name": "Ganesh vishal kumar",
    "gender": "Male",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b3c3a353e283375302e363a2969686f1b2f3c">@example.com</a>",
    "status": "active"
}

In the following test, I am generating an email ID programmatically and using it directly in the JSON body. However, I would like to use a JSON file fixture instead.

it('first post test', () => {
        var pattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        var emailId = "";

        for (var x = 0; x < 10; x++) {
            emailId = emailId + pattern.charAt(Math.floor(Math.random() * pattern.length));
        }
        emailId = emailId + '@test.org'
        cy.request({
            method: 'POST',
            url: 'https://gorest.co.in/public/v2/users',
            body: {
                "name": "Ganesh Kumar",
                "gender": "Male",
                "email": emailId,
                "status": "active"
            },
            headers: {
                'authorization': 'Bearer 18806c8605b08cabb3c9ce642cbc3a21e1a8942a96c3b908a7e0e27c3b5cf354'
            }
        }).then((res) => {
            expect(res.status).to.eq(201)
        })
    })

Answer №1

Why not simply do the identical process, but with fixture data instead?

In this scenario, we are harnessing the capability of combining an object's properties using a spread operator, followed by appending our new properties to the end of the list.

For further insight, please visit: Spread syntax (...)

  ...
  let emailId =  .. // calculation for email

  cy.fixture('my-fixture-file-that-has-most-of-the-data-required.json')
    .then(fixtureData => {
      const body = {...fixtureData, email: emailId}
      cy.request({
        ..
        body,              // include the body variable from previous line
        headers: {
          ...
      })

Answer №2

If you're looking to enhance your data mocking capabilities, check out this handy plugin

Easily create detailed fixture files in json format with almost all the functionalities of faker. Here's an example:

{
    "name": "Utilizing fixtures for realistic data representation ${faker.string.uuid()}",
    "email": "${faker.internet.email()}",
    "body": "Mock data with fixtures ${faker.string.uuid()} makes server responses more accurate",
    "int": "${faker.number.int()}",
    "intParam": "${faker.number.int(100)}",
    "intObjectParam": "${faker.number.int({ min: 10, max: 15 })}",
    "string": "${faker.string.numeric()}",
    "airline": "${faker.airline.flightNumber({ addLeadingZeros: true })}",
    "airline2": "${faker.airline.flightNumber({ length: { min: 2, max: 3 } })}",
    "color": "${faker.color.colorByCSSColorSpace({ format: 'css', space: 'display-p3' })}",
    "boolean": "${faker.datatype.boolean(0.9)}",
    "between": "${faker.date.between({ from: '2029-01-01T00:00:00.000Z', to: '2030-01-01T00:00:00.000Z' })}",
    "amount": "${faker.finance.amount({ min: 5, max: 10, dec: 5, symbol: '', autoFormat: true })}",
    "arrayElement": "${faker.helpers.arrayElement(['cat', 'dog', 'mouse'])}"
}

Full disclosure: I'm the developer behind this versatile plugin

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

Attempting to parse JSON data (with the help of GSON) into a Java object that contains another object within its fields

Currently, I am utilizing Google's GSON library to parse JSON strings. I have successfully implemented it for saving an Object called User using the following line of code: User user = gson.fromJson(string, User.class), However, I am facing difficul ...

Guide on extracting the keys from an object_construct and displaying them in their own distinct column

My data is structured in a table format. Here is an example: ID ALL_ATTRIBUTES ALL_FIELDS 1 {"name" : "JESSICA"} {"name"} 2 {"age": 15, "name": "JOSH"} {"age", "name" ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

I was able to use the formGroup without any issues before, but now I'm encountering an error

<div class="col-md-4"> <form [formGroup]="uploadForm" (ngSubmit)="onSubmit(uploadForm.organization)"> <fieldset class="form-group"> <label class="control-label" for="email"> <h6 class="text-s ...

Comparing JSON objects in Jackson and GSON for consistent and predictable results

Interestingly, Jackson does not support stable JSON object comparison as mentioned in this GitHub gist. This raises the question of whether GSON provides a solution for stable comparison of JSON objects without requiring custom overrides or implementatio ...

Using the jq tool, you can easily determine the total number of key-value pairs present in a specific JSON

Consider a JSON structure with the following schema: { "apple": "orange", "pear": 10, "banana": true } I am looking to determine how many key-value pairs exist within this JSON structure. While in JavaScript I ...

Top method for developing a cohesive single-page application

Many websites are incorporating JSON data in string format within their page responses, along with HTML: For example, take a look at The benefit of rendering JSON in string format within the page response is that it allows for the efficient loading of da ...

I continue to encounter the following error message: A system error occurred while attempting to convert 'AngularTest' into an Angular project

I encountered an issue while attempting to integrate Karma into my Eclipse project. The error occurred during the conversion process to AngularJS: While converting 'AngularTest' to an angular project, I faced the following internal error: loader ...

Issue with detecting window resize event in Angular 7 service

I have a unique service that utilizes a ReplaySubject variable for components, but strangely the WindowResize event isn't triggering. import { Injectable, HostListener } from '@angular/core'; import { ReplaySubject } from 'rxjs'; ...

The issue arises when Jest fails to align with a custom error type while utilizing dynamic imports

In my project, I have defined a custom error in a file named 'errors.ts': export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, Error.prototype); this.nam ...

Experiencing difficulties with loading Facebook wall feed JSON data

Struggling to integrate a Facebook wall feed using jQuery on my website's client side. Utilizing this URL for the Facebook request: Attempted approaches so far: 1. $.getJSON('http://www.facebook.com/feeds/page.php?format=json&id=407963083 ...

Issues with maintaining the checked state of radio buttons in an Angular 4 application with Bootstrap 4

In my Angular 4 reactive form, I am struggling with the following code: <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary" *ngFor="let item of list;let i=index" > <input type="radio" name="som ...

Can we convert oddly structured data to XML format?

I have some sample output data that resembles JSON but is not formatted exactly like it. I am curious about converting this data into XML format using PHP. Can someone help me with this? [{ action: 'getallregions', reply: [{ regionid: &a ...

generate a different identifier for ajax requests avoiding the use of JSON

The AJAX request functions in the following way: success: function(data) { $('#totalvotes1').text(data); } However, I need it to work with unique IDs as follows: success: function(data) { $('#total_' + $(this).attr("id")). t ...

Empty initial value of a number type input element in React using TSX

In the process of developing a react POS app using Typescript, I encountered an issue with calculating change when entering the amount of money received from a buyer. The problem arises when the first value passed to the change calculation logic is empty, ...

The introduction of an underscore alters the accessibility of a variable

When working in Angular, I encountered a scenario where I have two files. In the first file, I declared: private _test: BehaviorSubject<any> = new BehaviorSubject({}); And in the second file, I have the following code: test$: Observable<Object& ...

The typescript compiler encounters an error when processing code that includes a generator function

Recently, I started learning about TypeScript and came across the concept of generators. In order to experiment with them, I decided to test out the following code snippet: function* infiniteSequence() { var i = 0; while(true) { yield i++ ...

Save all hyperlinks into a JSON document using Python

I need to download numerous links from a .json file using a Python script. How can I accomplish this task effectively? Can anyone guide me on how to get started with the following code snippet? import urllib from urllib.request import urlopen import json ...

Is it feasible to have two distinct value_from conversions declared in separate namespaces when using boost::json?

Imagine having a class called Customer in the namespace Data. Utilizing the capabilities of boost, it is known that this can be converted into valid JSON by creating a function with the signature: void tag_invoke( const value_from_tag&, value& jv, ...

The expression has been altered following verification. It previously read as 'model: 1777' but now states 'model: 2222'

I've been working on this HTML code that utilizes [(ngModel)] to update input values, and I want the Total, Subtotal, and Amount Paid fields to be automatically calculated when a change is made. However, I'm encountering some issues with this app ...