Hey everyone! I wanted to share a small but impactful piece of work that is adding significant value to our automation tests with minimal effort. We’ve created a simple Cypress command that has contributed to nearly one-fourth of the total issues caught by our automation tests 🎉
The idea is straightforward: it checks that none of our pages are throwing API errors. If you’re new to Cypress, this is an easy and effective way to boost your testing without feeling overwhelmed.
How to set it up?
- Add a Custom Command in cypress/support/commands.js
Cypress.Commands.add("verifyApiStatus", (page, timeout, expectedStatusCodes) => {
// Intercept all API calls made to the specidied endpoint
cy.intercept(`/api/**).as(`${page}`);
// Navigate to the specified page (e.g., "/dashboard")
cy.visit(page);
// Wait for the specified duration to allow API call to complete (e.g., 10000 or 15000 milliseconds)
cy.wait(timeout);
// Check each intercepted API response
cy.get(`@${page}.all`).each((inteception)=>{
//verify that the response exist and has a status code
if (inteception.response && interception.response.statusCode){
// Assert that the status code matches on of the expected values
expect(interception.response.statusCode).to.be.oneOf(expectedStatusCodes);
}
});
});
- Create a test file in pageload.cy.js
it ('Verifies that the API for the dashboard and users page loads without errors'. function(){
// Include the steps to log in
// verify the API status for the dashboard page and users, expecting status codes 200, 201 or 404
cy.verifyApiStatus("/dashboard", 10000,[200,201,404]);
cy.verifyApiStatus("/users", [200,201,404]);
});
Why Is This Useful? 🤔
This small command has made a big difference for us. If an API call returns a status code like 500, the test will fail, alerting you to potential issues immediately. If you’re just starting with Cypress, using this command can save you time and help ensure your app is stable. Simple, powerful, and effective! 💥
👉🏻 By:Rojal Bati