Reputation: 460
I'm trying to detect how many times an API endpoint is called when running tests with Cypress, I'm stubbing out the endpoints with cy.intercept(). My code is like so:
cy.intercept("POST", "api/cancel/**", {
statusCode: 200,
}).as("cancel_contribution");
cy.intercept("PATCH", "/api/case/**", {
statusCode: 200,
body: {"message": "success"}
}).as("create_case_in_salesforce");
cy.visit("/");
cy.findByText("Manage recurring contribution").click();
cy.get('[data-cy="Cancel recurring contribution"]').click();
cy.findByText("Confirm cancellation").click();
cy.wait("@create_case_in_salesforce");
cy.wait("@cancel_contribution");
cy.get('[data-cy="cancellation_message"]');
expect('@create_case_in_salesforce').to.have.been.calledOnce;
expect('@cancel_contribution').to.have.been.calledOnce;
I'm trying to make sure these endpoints only get called once during the test run, but the last two lines are not valid, how could I achieve this?
Upvotes: 0
Views: 2994
Reputation: 2555
Your code has a mixture of async (cy.
) and sync(expect
) code. You can simply wrap the expect
's in a .then()
command.
cy.intercept("POST", "api/cancel/**", {
statusCode: 200,
}).as("cancel_contribution");
cy.intercept("PATCH", "/api/case/**", {
statusCode: 200,
body: {"message": "success"}
}).as("create_case_in_salesforce");
cy.visit("/");
cy.findByText("Manage recurring contribution").click();
cy.get('[data-cy="Cancel recurring contribution"]').click();
cy.findByText("Confirm cancellation").click();
// add .then() to check was called once
cy.wait("@create_case_in_salesforce").then(req => {
expect('@create_case_in_salesforce').to.have.been.calledOnce;
})
// add .then() to check was called once
cy.wait("@cancel_contribution").then(req => {
expect('@cancel_contribution').to.have.been.calledOnce;
})
cy.get('[data-cy="cancellation_message"]');
Upvotes: -1
Reputation: 1334
You can use @alias.all
feature of Cypress for this.
cy.wait("@create_case_in_salesforce");
cy.wait("@cancel_contribution");
cy.get("@create_case_in_salesforce.all").should('have.length', 1);
cy.get("@cancel_contribution.all").should('have.length', 1);
For more details see this thread
Upvotes: 4