Search code examples
javascriptpluginscypressaliascypress-intercept

Cypress sharing data (alias) between spec files


I need to use an alias I got after intercepting a cy.wait(@..) in other tests (in different files), but I am not sure how I could do it.

However, seems like it is possible if save the data in plugins/config space and then fetch using cy.task But I am not sure how to do it. Maybe someone could help me?

I am intercepting this request cy.intercept('POST', '**/quotes').as('abccreateQuote')

and as well I am getting the quote Id that comes in the response body.

cy.wait('@createQuote').then(({ response }) => {
        if (response?.statusCode === 201) {
          cy.wrap(response.body.data.id).as('abcQuoteId')
        }  
      })

I need to use this abcQuoteId alias in different tests and located it in different files.

to visit the page cy.visit(`quotes/${abcQuoteId}/show`)


Solution

  • A task would do it, but less code if you write to a fixture file

    cy.wait('@createQuote').then(({ response }) => {
      if (response?.statusCode === 201) {
        cy.writeFile('./cypress/fixtures/abcQuoteId.json', {abcQuoteId: response.body.data.id})
      }  
    })
    

    Advantage over task, you can check the fixture file manually in case of typos, should look like this:

    {
      "abcQuoteId": 123
    }
    

    and use it like this

    cy.fixture('abcQuoteId.json')
      .then(fixture => {
        const url = `quotes/${fixture.abcQuoteId}/show`
        console.log(url)                                  // quotes/123/show
        cy.visit(url)
      })