Home > Back-end >  How to add object into array in file in cypress
How to add object into array in file in cypress

Time:07-11

I have a file demoJ.json. It contains an array of objects

[{
  "name": "autoTest146",
  "email": "[email protected]",
  "pass": "password"
}]

Everytime if it needs necessary, I generate new user and their credentials. I want to add them into this file to use them in future tests. How can I do it?

thanks

CodePudding user response:

You can use the readFile and writeFile cypress methods to do this. Something like:

cy.readFile('cypress/fixtures/demoJ.json', (err, data) => {
  if (err) {
    return console.error(err)
  }
}).then((data) => {
  data[0].name = 'new Name'
  data[0].email = 'new Email'
  data[0].pass = 'new Password'
  cy.writeFile('cypress/fixtures/demoJ.json.json', JSON.stringify(data))
})

CodePudding user response:

If you need just to rewrite each time that file, simply use writeFile util:

cy.writeFile('/path/to/file.json', userObject)

In case you need to append and keep old ones, then go with readFile, writeFile and spread aperator:

cy.readFile('/path/to/file.json').then(userList => {
    cy.writeFile('/path/to/file.json', [...userList, newUserObject])
})
  • Related