I'm starting to use cypress and I wanted to do 2 test. One to verify what is displayed if my api return 'false' and one to what is on screen if my api return 'true'. I tried to do a simple test like this one :
context('contextTest', () => {
before(() => {
cy.waitLoading();
});
beforeEach(() => {});
it('false test', function() {
cy.intercept('POST', '**/test/alreadySent', {
fixture: 'test/alreadySent-false.json',
}).as('alreadySent');
cy.wait('@alreadySent');
cy.get('[data-cy=alreadysent-button]');
});
});
But the intercept doesn't work and it always return the true api call. What is strange is, if I just put the code in my before(), all work fine as expected.
context('contextTest', () => {
before(() => {
cy.intercept('POST', '**/test/alreadySent', {
fixture: 'test/alreadySent-false.json',
}).as('alreadySent');
cy.waitLoading();
});
beforeEach(() => {});
it('false test', function() {
cy.wait('@alreadySent');
cy.get('[data-cy=alreadysent-button]');
});
});
But I need to change the intercept for the next test so I wanted to set the intercept on this test exclusively.
Is it possible, why is my first code doesn't seem to work? Or should I write my next test on another file and it is a bad practice to do this kind of verification on the same file?
Since it works when the intercept is moved up in the command order, it seems that cy.waitLoading()
triggers the POST and not cy.get('[data-cy=alreadysent-button]')
.
The intercept must always be set up before the trigger (page visit or button click).
But the intercept varies between tests, so instead of before()
I would try setting up a helper function that is called at the top of each test.
const loadAndIntercept = (apiResult) => {
const apiFixture = apiResult ? 'test/alreadySent-true.json' : 'test/alreadySent-false.json';
cy.intercept('POST', '**/test/alreadySent', { fixture: apiFixture }).as('alreadySent');
cy.waitLoading();
})
it('false test', function() {
loadAndIntercept(false);
cy.wait('@alreadySent');
cy.get('[data-cy=alreadysent-button]');
});
it('true test', function() {
loadAndIntercept(true);
cy.wait('@alreadySent');
cy.get('[data-cy=alreadysent-button]');
});
This should work since intercepts are cleared between tests. Ref docs - intercept
Note: all intercepts are automatically cleared before every test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With