Reputation: 187
I'm fetching the real data via API and then check response is success or fail like this.
{ message: "fail" }
if the message is fail, I want to force test fail and also I want to check status is ok or not. Even if use throw new Error, testing is still success.
My codes like this
describe('fetch Data', () => {
beforeEach(() => {
cy.visit('http://localhost:3000');
});
it('Fetch Data', () => {
fetch('https://mocki.io/v1/82b25ba1-615a-4ff6-8c5d-c9f464f8c843').then((response) => {
if (!response.ok) {
throw new Error('Something went wrong!');
} else {
return response.json();
}
}).then((res) => {
expect(res.message).to.contain('success');
cy.log('result => ', res);
}).catch((err) => {
throw new Error(err);
});
});
});
Upvotes: 3
Views: 782
Reputation: 31924
Essentially the fetch()
and subsequent .then()
and .catch()
are not running on Cypress queue, so it does not know when the test has finished.
You can convert the fetch()
to cy.request()
to get around that.
But to continue with fetch, use Mocha's done()
method inside the catch block to signal end of test
it('Fetch Data', (done) => {
fetch('https://mocki.io/v1/82b25ba1-615a-4ff6-8c5d-c9f464f8c843')
.then((response) => {
if (!response.ok) {
throw new Error('Something went wrong!');
} else {
return response.json();
}
}).then((res) => {
expect(res.message).to.contain('success');
cy.log('result => ', res);
done()
})
.catch((err) => {
throw new Error(err);
done()
})
})
Removing the catch clause will also allow the test to fail.
it('Fetch Data', () => {
fetch('https://mocki.io/v1/82b25ba1-615a-4ff6-8c5d-c9f464f8c843')
.then((response) => {
if (!response.ok) {
throw new Error('Something went wrong!');
} else {
return response.json();
}
}).then((res) => {
expect(res.message).to.contain('success');
cy.log('result => ', res);
})
})
Upvotes: 3