Reputation: 389
I try to use Cypress to test my application. In this application I have a form, submitting it causes a POST API call. The API response contains the ID of the created resource. I would like to save this ID into a variable to reuse it later in my test (to clean the resource at the end of the test).
This is my Cypress code
describe('Templates', function() {
let templateID = null
before('before once', function() {
cy.server();
// define a route with alias for my POST requesst
cy.route({method: 'POST', url:'/api/templates/'}).as('api_template_create')
cy.visit('');
});
it('Create a new template', function() {
cy.get('.my-form #type').select('book')
cy.get('.my-form #title').type('Cyress title test')
...
cy.get('.my-form input:submit').click()
cy.wait('@api_template_create').then(xhr => {
const response = xhr.response.body
templateID = response.metadata.pid
cy.log(templateID) // at this time 'templateID' contains the correct value
})
cy.wait(2000)
cy.log(templateID) // templateID is null (as initial value)
// continue test....
// ...at the end call the DELETE API with templateID as param
});
});
See below the result of this code:
L#23 is the log into the wait().then() --> correct one
L#25 is the log after in the main 'it' test --> return to null (as initial value)
Is it a way to solve my problem?
Upvotes: 1
Views: 3646
Reputation: 18650
You can write the id into a fixture file and then re-use it throughout your tests. You can look into the Cypress Fixtures Docs.
describe('Templates', function () {
let templateID = null
before('before once', function () {
cy.server();
// define a route with alias for my POST requesst
cy.route({ method: 'POST', url: '/api/templates/' }).as('api_template_create')
cy.visit('');
});
it('Create a new template', function () {
cy.get('.my-form #type').select('book')
cy.get('.my-form #title').type('Cyress title test')
//...
cy.get('.my-form input:submit').click()
cy.wait('@api_template_create').then(xhr => {
const response = xhr.response.body
templateID = response.metadata.pid
cy.log(templateID)
//Write the id into a fixtures file
cy.writeFile('cypress/fixtures/testdata.json', { id: templateID })
}).then(function () {
cy.wait(2000)
//Access Value from Fixtures file
cy.fixture('cypress/fixtures/testdata.json').then(function (testdata) {
cy.log(this.testdata.id)
})
})
})
})
Upvotes: 1