Skip to content

How to launch Cypress test with Chrome Incognito Mode?

Published: at 08:40 PM

Running tests in incognito mode can be incredibly useful for keeping your testing environment clean and predictable. In this guide, we’ll cover why you might want to run Cypress tests in incognito, the advantages of doing so, and the potential pitfalls of testing in a normal browser window.

cypress-incog

Why Launch Cypress in Incognito Mode?

When you run tests in a regular browser session, data from previous sessions—like cookies, history, and cache—can affect the results. Incognito mode, on the other hand, starts fresh each time, which means you can avoid interference from any stored data and focus on testing the actual functionality.

Advantages of Testing in Incognito Mode

  1. Data Isolation: Incognito mode prevents cached data, cookies, and login sessions from impacting test results. This is especially helpful when testing login flows or session management, where residual data can interfere.

  2. Consistent Results: Running tests in incognito mode helps you avoid issues caused by leftover data, resulting in more reliable and consistent test results.

  3. Efficient Debugging: With incognito, you don’t need to clear cache or cookies between tests, saving time and making it easier to debug issues without extra steps.

Common Issues in a Normal Browser Window

When running Cypress tests in a normal browser session, some common issues include:

How to Configure Cypress to Launch in Incognito Mode

To run Cypress tests in Chrome’s incognito mode, configure Cypress to pass the --incognito flag in cypress.config.js file when launching Chrome. Here’s how to do it:

const { defineConfig } = require("cypress");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('before:browser:launch', (browser = {}, launchOptions) => {
        if (browser.family === 'chromium' && browser.name !== 'electron') {
          launchOptions.args.push("--incognito");
          return launchOptions;
        }
      });
    },
  },
});

Adding this code will ensure that each time Cypress launches Chrome, it will open in incognito mode, providing a fresh, isolated environment for each test.

Final Thoughts

Running Cypress tests in incognito mode can be a game-changer for isolating test environments and improving reliability. While it might not be necessary for every test case, it’s an invaluable tool when testing complex user flows or managing multiple sessions. Try it out, and see how it simplifies your workflow!