Reputation: 2619
I am running my list of Cypress tests against my application within a staging environment.
The docs say to use the before
hook to remove data however I don't know the ID of the row until I've run the test and added it so this isn't possible.
describe('Entity Page', () => {
before(() => {
const { username, password } = Cypress.env();
cy.login(username, password);
cy.addEntity(name, email, mobile, {});
cy.wait(3000);
cy.get('@id').then(id => {
cy.visit(`/entity/${id}`)
cy.wait(6000)
});
});
it('form contains new entity details', () => {
cy.get('[data-testid=title]').should('have.text', name);
});
after(() => {
cy.get('@id').then(id => {
cy.log('removing ID ', id);
if (id) {
cy.deleteEntity(id);
}
});
});
});
I can't see a way that I can run my delete within the before without knowing the ID that the entity gets generated. However, this then leads to issues if the delete fails within my after block as other tests don't run.
Is there a recommended way of performing actions like this when you don't know the identifier before the test starts?
Upvotes: 3
Views: 1753
Reputation: 32118
Since the details of your db are hidden, it's hard to be specific but you want something that does cy.deleteAllIds()
.
If not that, then write the id to a fixture
cy.get('@id').then(id => {
cy.writeFile('cypress/fixtures/idToDelete.json', {id})
...
})
and in the before()
before(() => {
cy.fixture('idToDelete.json').then(data => {
if (data.id) cy.deleteEntity(data.id)
cy.writeFile('cypress/fixtures/idToDelete.json', {})
})
})
Also (this may or may not work) the reason you aren't supposed to use after()
is because a failing test might skip the after hook.
So you can catch the fail event and delete the id there (but keep the after()
for the success path).
cy.on('fail', () => {
cy.get('@id').then(id => {
cy.log('removing ID ', id);
if (id) cy.deleteEntity(id);
})
})
Upvotes: 3