https://cypress.io logo
Hello, I'm struggling with intercepting a POST, I ...
# e2e-testing
t
Hello, I'm struggling with intercepting a POST, I hope somebody can help me see what I am doing wrong. I have an API call (POST) that I want to make sure completes before the script continues. This call is executed in a beforeEach and I noticed that the test already starts running before this API call is completed, which sometimes leads to a failure. So I wanted to cy.wait() for it. I got it to work partially, but the following example also catches a GET on the same endpoint, and I only want it to intercept POST:
Copy code
export function postRequest() {
  const endpoint = '/some/path';
  const url = `http://example.com${endpoint}`;
  const alias = 'postRequest';

  const params = {
    method: 'POST',
    url: url,
    body: createJsonBody(),
  };

  cy.intercept(url).as(alias);
  cy.request(params);
  cy.wait(`@${alias}`);
}
I would expect this variation to work, but it doesn't intercept this request
Copy code
export function postRequest() {
  const endpoint = '/some/path';
  const url = `http://example.com${endpoint}`;
  const alias = 'postRequest';

  const params = {
    method: 'POST',
    url: url,
    body: createJsonBody(),
  };

  cy.intercept({ method: 'POST', url: url }).as(alias);
  cy.request(params);
  cy.wait(`@${alias}`);
}
I have also tried these variations, they all do not intercept the request:
Copy code
cy.intercept('POST', url).as(alias);
cy.intercept('POST', endpoint).as(alias);
cy.intercept('POST', `**${endpoint}`).as(alias);
cy.intercept({ method: 'POST', path: endpoint}).as(alias);
cy.intercept({ method: 'POST', path: url}).as(alias);
cy.intercept({ method: 'POST', path: `**${endpoint}`}).as(alias);

cy.intercept(url, (req) => {
    if (req.method === 'POST') {
      req.alias = alias;
    }
});
Also tried with a lowercase alias, since I read somewhere that was a known issue. This GET intercept works fine (but ofcourse only on the GET):
cy.intercept('GET', endpoint).as(alias);