How to reuse mocked Cypress tests to run against real APIs?

Viewed 177

I have Cypress tests that run with local mocks/fixtures using cy.intercept.

I'd like to reuse these tests to run against a production URL and disable the network interception so that the tests run against real APIs.

Is these a way to disable all cy.intercepts, or am I thinking in the wrong direction?

2 Answers

The Intercepted Requests section will help you achieve this, but you might have to rewrite your cy.intercept() calls.

As stated, you need to use the routeHandler to apply a condition to stub or not you api calls.

cy.intercept('GET', '/yourEndpoint', (req) => {
    if (Cypress.config('baseUrl') === 'prodUrl') {
        req.continue();
    } else {
        req.reply(your stub here);
    }
});

Edit: Example of cy.intercept() overwrite

I suppose you are using one of these cy.intercept() signatures: enter image description here

In that case, you would need to use the Cypress.Commands.overwrite() to transform your staticResponse variable into a routeHandler callback to end up with one of these: enter image description here

Here's an example with the second signature (method, url, staticResponse):

Cypress.Commands.overwrite('intercept', (originalFn, method, url, staticResponse) => {
    originalFn(method, url, (req) => {
        if (Cypress.config('baseUrl') === 'prodUrl') {
           req.continue();
        } else {
           req.reply(staticResponse);
        }
    });
});

If you use multiple signatures, you would need a logic to accept 2 or 3 parameters and map them accordingly to originalFn().

There is a plugin "cypress-skip-test". It's possible to skip tests or code blocks depending on OS, browser or environment variables. Assuming that you set your interceptors in before or beforeEach you can put a "onlyOn" or "skipOn" around the interceptor call. Depending on a environment "production" you skip the setting of the interceptors.

You call:

CYPRESS_ENVIRONMENT=production npx cypress run

and you skip:

beforeEach(() => {
  skipOn('production', () => {
    cy.intercept(...);
  })
});
Related