0

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?

Jon Flynn
  • 440
  • 6
  • 15

2 Answers2

4

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

Lukasz Gawrys
  • 1,234
  • 2
  • 8
-1

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"]');
jjhelguero
  • 2,281
  • 5
  • 13