Search code examples
reactjscypresscypress-testing-library

Cypress intercept, detect how many times API was called


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?


Solution

  • 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