Reputation: 17
I'm using a node library to execute api calls for test data setup and teardown. The library works as follows:
someApiServiceObject
.executeApiCall({... parameters})
.then(doSomethingWithResults())
.catch(() => {
// Here I would like to fail the test as something has gone wrong
})
If the request fails for some reason, I only learn about it by the Promise returning from executeApiCall
function being rejected - hence the catch block.
But if I put throw new Error();
into the catch block or remove the catch block, I can see the (uncaught exception) Error:
in the cypress console, but the test still passes.
Can someone advise me on how this case should be handled correctly?
The test:
it('List projects', () => {
projectsApi.projectsList({})
.then(() => {
cy.log('Success');
}).catch(() => {
throw new Error();
});
});
Upvotes: 0
Views: 699
Reputation: 32138
If you call someApiServiceObject.executeApiCall({...parameters})
in a task (since it's a node library), you should just be able to return the promise and Cypress handles failing the test. Don't catch()
within the task.
module.exports = (on, config) => {
on('task', {
api(parameters) {
return someApiServiceObject
.executeApiCall({... parameters})
.then(doSomethingWithResults())
},
})
}
If that fails, follow this pattern Return number of files in the folder
module.exports = (on, config) => {
on('task', {
countFiles(folderName) {
return new Promise((resolve, reject) => {
someApiServiceObject
.executeApiCall({... parameters})
.then(doSomethingWithResults())
.then((results) => resolve(results))
.catch((err) => reject(err))
})
})
},
})
}
From comments, I think there's a assumption being made that .executeApiCall()
must be returning a promise, but that may not be the case.
For example cy.get(...)
has a .then(...)
method, but it does not return a promise, it just has a .then()
method.
If .executeApiCall()
does actually return a promise, the first example is all you need. If it does not, you need to wrap the code.
Cypress will recognise a promise returned from a task, and use resolve
or reject
accordingly.
Upvotes: 1