restcypress

Update an item of json file, with new value


I am using an external json file as payload to a POST request in Cypress, like this

cy.fixture('createUsers.json').then((requestBody) => {
  cy.request('POST', /api/vi/createUsers, requestBody).then(function (res) {
    localStorage.setItem('token', res.body.token);
    localStorage.setItem('refreshToken', res.body.refreshToken);
  });
});

The json file looks like this

    {
        "carID": "HND",
        "from": 1683579600000,
        "to": 1683579600000,
        "launched": true,
        "lftl": false,
        "dmtr": null,
        "acxzId": "HND_PRE"
    }

I want to keep from and to fields as dynamic. This is Unix time stamp for today's date.

I am able to achieve this if I am passing payload in the fixture code, not via an external file like this

let testDate = Date.parse(new Date().toLocaleDateString("en-US"));
cy.request('POST', /api/vi/createUsers,
  {
    "carID": "HND",
    "from": testDate,
    "to": testDate,
    "launched": true,
    "lftl": false,
    "dmtr": null,
    "acxzId": "HND_PRE"
}
).then(function (res) {
  localStorage.setItem('token', res.body.token);
  localStorage.setItem('refreshToken', res.body.refreshToken);
});

So, how can I pass today's date, when I want to pass JSON payload using an external file?


Solution

  • Seems pretty straight forward, import the fixture and modify the dates

    cy.fixture('createUsers.json')
      .then(data => {
    
        // here I can easily modify those parts I want to be "dynamic"!
    
        data.from = Date.parse(new Date().toLocaleDateString("en-US")) 
    
        cy.request('POST', /api/vi/createUsers, data).then(
          ...
        )
      })