Andrei Nico
Andrei Nico

Reputation: 89

Unable to read data from fixture file after writing it

I'm writing a URL with an ID in a .json file that I'm extracting from the API, but the problem is that the cy.log() is printing the data before it is wrote in the file. Because the AppelData.json has the written data, but cy.log() prints nothing. After the second run, the cy.log() prints the previous data from AppelData.json.

So how do I make, that cy.log() to print the data from AppelData.json only after it is been written?

describe('Creer un appel modal', () => {

    beforeEach(() => {

        cy.fixture('AppelData').then(function(data) {
            this.AppelData = data
        })

        cy.visit('/')
        cy.loginAsAdmin()
       

    })

    it('Create an intervention request using existing site', function() {

        navigateTo.plusAppelButton()
        onAppelModal.SelectSite(this.AppelData.Site)
        onAppelModal.SelectMetier(this.AppelData.Metier)
        onAppelModal.FillMotif(this.AppelData.Motif)

        cy.intercept('POST','/documents/datatable/intervention_request/**').as('response')
            cy.contains('Valider').click()
            cy.wait('@response').get('@response').then(xhr => {
                console.log(xhr)
                cy.readFile('cypress/fixtures/AppelData.json').then(AppelData => {
                AppelData.AppelID = xhr.request.url.replace(/\D/g,'').replace(/3/, '')
                cy.writeFile('cypress/fixtures/AppelData.json', AppelData) 
                cy.log(this.AppelData.AppelID) // logs no value on the first run, and prints old value from the 2nd run
                })
 
            })
    })
})

Thank you!!

Upvotes: 1

Views: 725

Answers (1)

Alapan Das
Alapan Das

Reputation: 18650

Assuming that that the value is updated into the fixtures file, you can do this:

it('Create an intervention request using existing site', function () {
  navigateTo.plusAppelButton()
  onAppelModal.SelectSite(this.AppelData.Site)
  onAppelModal.SelectMetier(this.AppelData.Metier)
  onAppelModal.FillMotif(this.AppelData.Motif)
  cy.intercept('POST', '/documents/datatable/intervention_request/**').as(
    'response'
  )
  cy.contains('Valider').click()
  cy.wait('@response')
    .get('@response')
    .then((xhr) => {
      console.log(xhr)
      cy.readFile('cypress/fixtures/AppelData.json').then((AppelData) => {
        AppelData.AppelID = xhr.request.url.replace(/\D/g, '').replace(/3/, '')
        cy.writeFile('cypress/fixtures/AppelData.json', AppelData)
      })
    })

  cy.readFile('cypress/fixtures/AppelData.json').then((AppelData) => {
    cy.log(AppelData.AppelID)
  })
})

Upvotes: 1

Related Questions