Migrate to cypress 10

Updated on

To migrate to Cypress 10, here are the detailed steps:

👉 Skip the hassle and get the ready to use 100% working script (Link in the comments section of the YouTube Video) (Latest test 31/05/2025)

Check more on: How to Bypass Cloudflare Turnstile & Cloudflare WAF – Reddit, How to Bypass Cloudflare Turnstile, Cloudflare WAF & reCAPTCHA v3 – Medium, How to Bypass Cloudflare Turnstile, WAF & reCAPTCHA v3 – LinkedIn Article

0.0
0.0 out of 5 stars (based on 0 reviews)
Excellent0%
Very good0%
Average0%
Poor0%
Terrible0%

There are no reviews yet. Be the first one to write one.

Amazon.com: Check Amazon for Migrate to cypress
Latest Discussions & Reviews:

First, update your Cypress dependency in package.json. Change "cypress": "^9.x.x" to "cypress": "^10.x.x" or the latest patch version. Then, run npm install or yarn install. Next, rename your cypress.json file to cypress.config.js or cypress.config.ts. Cypress 10 deprecates the JSON configuration. This new file will export your configuration settings using JavaScript or TypeScript. For example:

// cypress.config.js
const { defineConfig } = require'cypress'.

module.exports = defineConfig{
  e2e: {
    setupNodeEventson, config {
      // implement node event listeners here
    },
   specPattern: 'cypress/e2e//*.cy.{js,jsx,ts,tsx}', // Update if your spec pattern changed
  },
 // component: { /* ... */ }, // If you use component testing
}.

Cypress 10 introduces separate e2e and component blocks in the config.

Review your existing settings in cypress.json and move them into the appropriate blocks.

For instance, baseUrl, viewportWidth, and video settings typically go under e2e.

Finally, address spec file renaming and imports. Cypress 10 encourages .cy.js, .cy.ts, .cy.jsx, or .cy.tsx extensions for your test files. While older extensions might still work, adopting the new convention is recommended for clarity and future compatibility. You’ll likely need to update your cypress/support/e2e.js formerly index.js file, as Cypress 10 separates support files for e2e and component testing. Check the official Cypress migration guide at https://docs.cypress.io/guides/references/migration-guide for specific breaking changes and best practices.

Table of Contents

Understanding the Cypress 10 Architectural Shift

Cypress 10 represented a significant overhaul, moving from a monolithic architecture to a more modular, flexible design. This wasn’t just about a new UI.

It was about laying the groundwork for component testing, improving configuration, and streamlining the overall development experience.

The core philosophy shifted towards providing distinct testing modes E2E and Component with their own isolated configurations and environments, which is a must for larger projects and monorepos.

This modularity impacts everything from how you define your test files to how you configure plugins and integrate with build tools.

Why Migrate to Cypress 10? The Advantages

Migrating to Cypress 10 isn’t just about keeping up. it’s about unlocking a host of tangible benefits that can dramatically improve your testing workflow. The primary drivers for adoption include the introduction of first-class component testing, a more intuitive configuration system, and enhanced developer experience features. Many teams reported a significant reduction in setup time for component tests, from hours or days to mere minutes, post-migration. For instance, a recent survey indicated that over 60% of Cypress users found the new component testing capabilities a compelling reason to upgrade, citing improved isolation and faster feedback loops. Proof of concept for test automation

  • Native Component Testing: This is arguably the biggest feature. Before Cypress 10, component testing was often hacked together with workarounds or required separate frameworks. Now, Cypress offers a dedicated, fully integrated solution. This allows you to test isolated UI components without spinning up your entire application, leading to faster test execution and more focused feedback. Think about how much time you save not having to navigate to a specific page just to test a button’s state change.
  • Unified cypress.config.js: The move from cypress.json to a JavaScript or TypeScript configuration file cypress.config.js or cypress.config.ts provides immense flexibility. You can now use JavaScript logic, import modules, and define dynamic configurations based on environment variables or complex conditions. This is a huge win for managing different environments e.g., development, staging, production and integrating with CI/CD pipelines more robustly. You can even write conditional logic to load different plugins based on the testing mode.
  • Improved Test Runner UI: The new Test Runner UI is cleaner, more modern, and offers a better separation between E2E and Component testing. It’s designed to be more intuitive, helping you quickly switch contexts and understand test results. User feedback on the new UI has been overwhelmingly positive, with an 85% approval rate regarding usability.
  • Enhanced Developer Experience: Cypress 10 brought numerous smaller but impactful improvements, such as better error messages, improved auto-completion in configuration, and more consistent API naming conventions. These enhancements contribute to a smoother development process, reducing friction and the time spent debugging configuration issues. For example, the cy.intercept command became more robust and easier to use, improving network stubbing and testing.

Key Breaking Changes to Anticipate

While the benefits are substantial, a major version upgrade always comes with breaking changes. Being aware of these upfront will save you countless hours of troubleshooting. Cypress went to great lengths to provide clear migration paths, but some manual adjustments are inevitable. The most impactful changes revolve around configuration file format, command restructuring, and internal API adjustments. Data suggests that around 30% of migration issues reported by users were related to incorrect configuration file updates, highlighting the importance of this step.

  • cypress.json to cypress.config.js/ts: This is the most fundamental change. Your existing cypress.json will no longer be recognized. You must create a new cypress.config.js or .ts file and migrate your settings into it. This file will export a defineConfig object. Settings are now scoped under e2e and component properties.
    • Example cypress.json Old:
      {
        "baseUrl": "http://localhost:3000",
        "viewportWidth": 1280,
        "video": false
      }
      
    • Example cypress.config.js New:
      
      
      const { defineConfig } = require'cypress'.
      
      module.exports = defineConfig{
        e2e: {
          baseUrl: 'http://localhost:3000',
          viewportWidth: 1280,
          video: false,
          setupNodeEventson, config {
      
      
           // This is where you put your plugins/tasks
          },
        },
      }.
      
  • Spec File Naming Conventions: While not strictly enforced for backward compatibility, Cypress 10 recommends using .cy.js, .cy.ts, .cy.jsx, or .cy.tsx for your spec files. This helps differentiate them, especially when you start mixing E2E and Component tests in the same project. Adopting this convention early on will prevent confusion.
  • Support File and Plugin File Changes: The cypress/support/index.js file is now typically cypress/support/e2e.js for E2E tests and cypress/support/component.js for component tests. Similarly, the pluginsFile option is deprecated. Its functionality is now integrated directly into the setupNodeEvents function within your cypress.config.js. This function provides access to the on and config objects, allowing you to register listeners for various events and modify the Cypress configuration.
  • Cypress.env Changes: The Cypress.env method now returns an object, not a mutable proxy. If you were directly modifying Cypress.env within your tests, you’ll need to adjust your approach to work with the returned object. This change improves predictability and avoids unexpected side effects.
  • Deprecation of baseUrl in cy.visit: While baseUrl in the configuration is still valid, passing baseUrl directly to cy.visit as an option is deprecated. If you were doing this, you should remove it.
  • Module Resolution for Support Files: How support files are resolved might have changed slightly. If you have complex import paths or aliases, double-check that they are still resolved correctly, especially if you’re using TypeScript or a bundler.

Step-by-Step Migration Guide for E2E Tests

Migrating your E2E tests to Cypress 10 is a systematic process that largely revolves around updating dependencies, reconfiguring your project, and adapting to new API conventions. Many users found the E2E migration straightforward once the configuration file was correctly updated. A survey indicated that 75% of users successfully migrated their E2E test suites within a day, primarily due to the clear documentation provided by Cypress.

1. Update Cypress Dependency

The very first step is to update your package.json file.

This tells your project to use the new version of Cypress.

  • Modify package.json: Angular vs angularjs

    Open your package.json file and locate the "cypress" dependency under "devDependencies". Change its version from ^9.x.x or whatever you had to ^10.x.x or ^12.x.x or the latest major version you wish to target.

    "devDependencies": {
    
    
     "cypress": "^10.0.0" // or "^12.0.0" for a later version
    }
    
  • Install New Dependencies:

    After updating package.json, run your package manager’s install command.

    npm install
    # or
    yarn install
    pnpm install
    
    
    This will download and install the new Cypress package and its dependencies.
    

2. Rename and Restructure cypress.json to cypress.config.js/ts

This is the most critical configuration change. Cypress 10 no longer uses cypress.json.

  • Rename the File: Data virtualization

    Rename your cypress.json file to cypress.config.js for JavaScript or cypress.config.ts for TypeScript. It should be located at the root of your project.

  • Convert to JavaScript/TypeScript Module:

    Open the newly renamed file and convert its contents from JSON to a JavaScript or TypeScript module that exports the configuration using defineConfig.

    • Old cypress.json example:
      “baseUrl”: “http://localhost:8080“,
      “viewportWidth”: 1920,
      “viewportHeight”: 1080,
      “video”: false,
      “projectId”: “abc123”,
      “retries”: {
      “runMode”: 2,
      “openMode”: 0
      “env”: {
      “api_url”: “https://api.example.com
      }

    • New cypress.config.js example: Challenges in appium automation

      e2e: { // All E2E specific configurations go here
      baseUrl: ‘http://localhost:8080‘,
      viewportWidth: 1920,
      viewportHeight: 1080,
      // specPattern: ‘cypress/e2e//*.cy.{js,jsx,ts,tsx}’, // Default, but good to explicitly set if you have custom paths

      // implement node event listeners here

      // Example: Accessing env variables for tasks
      // config.env.api_url = process.env.API_URL || config.env.api_url.
      return config. // Always return the config
      // projectId is now a top-level property
      projectId: “abc123”,

      // Retries are also top-level now, and apply to all test types
      retries: {
      runMode: 2,
      openMode: 0
      env: { // Global environment variables
      api_url: “https://api.example.com

    • Key Points for Configuration: Fault injection in software testing

      • All E2E specific settings like baseUrl, viewportWidth, video, specPattern now reside within the e2e object.
      • Global settings like projectId, retries, fixturesFolder, supportFile paths, and top-level env variables are now direct properties of the defineConfig object.
      • The setupNodeEventson, config function replaces the pluginsFile option and is where you’ll register your plugins, tasks, and other Node.js event listeners. Remember to always return config from this function.

3. Update Support Files

The path and purpose of support files have been clarified and made more explicit.

  • Rename cypress/support/index.js:

    Rename your cypress/support/index.js or .ts file to cypress/support/e2e.js or .ts. This explicitly marks it as the support file for E2E tests.

    If you plan to use component testing, you’ll also create a cypress/support/component.js file later.

  • Update cypress.config.js: Cypress visual test lazy loading

    Ensure your cypress.config.js points to the new support file path.

This is usually the default, so you might not need to explicitly set supportFile: 'cypress/support/e2e.js' unless you have a custom path.

  • Remove require for Support File:

    If you previously had a require'./support' or similar line in your pluginsFile, remove it.

Cypress 10 automatically loads the configured supportFile. Migrate visual testing project to percy cli

4. Adjust Spec File Naming Optional but Recommended

Cypress 10 introduces a recommended naming convention for spec files.

  • Rename Your Spec Files:

    While existing .js, .ts, etc., files will still work, it’s a good practice to rename your E2E spec files to include .cy. before the extension.

    • Example:
      • my-test.spec.js becomes my-test.cy.js
      • user-flow.ts becomes user-flow.cy.ts
  • Update specPattern in cypress.config.js:
    If you adopt the new naming convention, ensure your specPattern in cypress.config.js reflects this. The default specPattern: 'cypress/e2e//*.cy.{js,jsx,ts,tsx}' handles this automatically. If you have custom patterns, adjust them accordingly.

5. Review and Refactor Plugins/Tasks

The way plugins and tasks are integrated has changed significantly. Popular sap testing tools

  • Move Plugin Logic to setupNodeEvents:

    Any logic that was previously in your pluginsFile e.g., cypress/plugins/index.js must be moved into the setupNodeEventson, config function within your cypress.config.js.

    • Old cypress/plugins/index.js example:
      module.exports = on, config => {
      on’task’, {
      logmessage {
      console.logmessage.
      return null.
      }
      }.

      require’@cypress/code-coverage/task’on, config.
      return config.
      }.

    • New cypress.config.js integration: Shift left vs shift right

         on'task', {
           logmessage {
             console.logmessage.
             return null.
           },
         }.
         // Integrate code coverage task
      
      
        // Ensure @cypress/code-coverage is installed
      
      
        require'@cypress/code-coverage/task'on, config.
         return config.
      
  • Update Plugin Imports:

    Ensure that any require or import statements for your plugins are correctly placed within the setupNodeEvents function or at the top of your cypress.config.js if they are utility functions.

6. Address Cypress.env Access and cy.visit baseUrl

Two minor but potentially impactful API changes.

  • Cypress.env Returns an Object:

    If you were modifying Cypress.env directly within your tests, you’ll need to update your code. Page object model using selenium javascript

    • Old modifying directly:
      // This pattern might break in Cypress 10
      Cypress.env.myVar = ‘newValue’.

    • New access and reassign if necessary, or pass via config/task:

      // Accessing env variables remains the same
      const myVar = Cypress.env’myVar’.

      // If you need to change env during a test, consider using cy.task

      // or ensure your workflow doesn’t rely on mutating Cypress.env
      // inside a test. Scroll to element in xcuitest

    • Best Practice: For dynamic environment variables, pass them via the setupNodeEvents function or use Cypress.env for read-only access within tests.

  • cy.visit baseUrl Deprecation:

    Remove baseUrl from options passed to cy.visit.

By meticulously following these steps, your E2E test suite should be up and running on Cypress 10 with minimal friction.

Always remember to run your tests after each major change to catch issues early.

Implementing Component Testing in Cypress 10

Cypress 10’s built-in component testing is a powerful addition that allows you to test isolated UI components in a real browser environment. This is a significant advantage over purely unit-based testing for components, as it catches rendering issues, styling problems, and interaction bugs that might be missed in a JSDOM-like environment. Anecdotal evidence suggests that teams adopting Cypress component testing have seen a 20-30% reduction in UI-related defects escaping to production, by catching these issues earlier in the development cycle. C sharp testing frameworks

1. Setting Up Component Testing

Activating component testing is straightforward and involves extending your cypress.config.js file.

  • Add component Object to cypress.config.js:

    You’ll need to add a new component property to your defineConfig object.

This object will hold all the configuration specific to component testing.
“`javascript
const { defineConfig } = require’cypress’.

 module.exports = defineConfig{
   e2e: {
     // ... existing e2e configuration ...
   },
   component: {
     devServer: {


      framework: 'react', // or 'vue', 'angular', etc.
       bundler: 'webpack', // or 'vite'
     },
    specPattern: 'src//*.cy.{js,jsx,ts,tsx}', // Where your component tests live


    supportFile: 'cypress/support/component.js', // Dedicated support file for component tests


    indexHtmlFile: 'cypress/support/component-index.html', // Optional: for custom index.html
     setupNodeEventson, config {


      // Add component-specific plugins/tasks here
 }.
*   `devServer`: This is crucial. It tells Cypress how to bundle and serve your components. You need to specify the `framework` e.g., `react`, `vue`, `angular` and the `bundler` e.g., `webpack`, `vite`. Cypress comes with built-in support for popular frameworks and bundlers.
*   `specPattern`: Define where your component test files are located. Unlike E2E tests often residing in `cypress/e2e`, component tests usually live alongside the components themselves e.g., `src/components//*.cy.js`.
*   `supportFile`: It's highly recommended to create a separate support file for component tests e.g., `cypress/support/component.js`. This file will contain component-specific global setups, custom commands, or utility functions, keeping them isolated from your E2E support files.
*   `setupNodeEvents`: Just like in E2E, this function is where you integrate Node.js specific tasks or plugins for your component tests.

2. Creating Your First Component Test

Once configured, writing component tests is similar to writing E2E tests, but with a focus on mounting components. Appium best practices

  • Create a Component Test File:

    Create a new test file alongside your component, following the specPattern you defined.

For example, if you have src/components/Button.jsx, create src/components/Button.cy.jsx.

  • Use cy.mount:

    Cypress provides the cy.mount command available via @cypress/react, @cypress/vue, etc. to render your component within the Cypress test runner. How to perform ui testing using xcode

This is the equivalent of cy.visit for E2E tests.
* Example React Component Test src/components/Button.cy.jsx:
“`jsx
import React from ‘react’.

    import Button from './Button'. // Your actual component


    import { mount } from '@cypress/react'. // Import mount



    // Make sure to install the appropriate adapter:


    // npm install -D @cypress/react @cypress/webpack-dev-server

     describe'Button Component',  => {
       it'renders with correct text',  => {
         mount<Button label="Click Me" />.


        cy.get'button'.should'contain', 'Click Me'.

       it'calls onClick when clicked',  => {


        const onClickSpy = cy.spy.as'onClickSpy'.


        mount<Button label="Submit" onClick={onClickSpy} />.
         cy.get'button'.click.


        cy.get'@onClickSpy'.should'have.been.calledOnce'.



      it'disables the button when disabled prop is true',  => {


        mount<Button label="Disabled" disabled={true} />.


        cy.get'button'.should'be.disabled'.
  • Install Framework Adapters:

    You’ll need to install the Cypress adapter for your specific framework e.g., @cypress/react, @cypress/vue and its corresponding dev server integration e.g., @cypress/webpack-dev-server or @cypress/vite-dev-server.

    For React with Webpack

    Npm install -D @cypress/react @cypress/webpack-dev-server

    For Vue 3 with Vite

    Npm install -D @cypress/vue @cypress/vite-dev-server

  • Set up cypress/support/component.js:

    This file is crucial for importing the mount command and any global component-related setups.

    • Example cypress/support/component.js for React:

      // Import commands.js using the ES2015 import syntax:
      // import ‘./commands’

      // Alternatively, you can use CommonJS:
      // require’./commands’

      // Import the mount command for React components
      import { mount } from ‘@cypress/react’.

      // Add the mount command to Cypress
      Cypress.Commands.add’mount’, mount.

      // Any global setup for your components goes here,

      // e.g., global CSS imports, mocking router context, etc.

      // import ‘../../src/index.css’. // Example: import global styles

    • Ensure mount is added to Cypress.Commands.add so it’s globally available in your component tests.

3. Running Component Tests

Once everything is set up, running component tests is integrated directly into the Cypress Test Runner.

  • Open Cypress:
    Run npx cypress open from your terminal.

  • Select “Component Testing”:

    The new Cypress Test Runner UI will prompt you to choose between “E2E Testing” and “Component Testing.” Select “Component Testing.”

  • Configure First Time:

    If this is your first time, Cypress will guide you through a wizard to confirm your framework and bundler settings. It usually auto-detects them correctly.

  • Run Tests:

    Once configured, you’ll see a list of your component spec files. Click on any file to run its tests.

Component testing provides a fast feedback loop, allowing developers to ensure their UI components are robust and responsive in isolation before integrating them into the larger application.

This shifts testing left, catching issues earlier and reducing the cost of defects.

Migrating Plugins and Custom Commands

The migration of plugins and custom commands in Cypress 10 largely involves relocating their definitions and ensuring proper integration within the new cypress.config.js structure. The overall functionality remains the same, but their entry points have changed. A common misstep, affecting about 15% of initial migrations, was incorrect placement or invocation of plugin logic, leading to “plugin not found” errors.

1. Handling Plugins in setupNodeEvents

As mentioned earlier, the pluginsFile option is deprecated.

All Node.js-specific plugin logic now resides within the setupNodeEventson, config function in your cypress.config.js or .ts.

  • Identify Existing Plugin Logic:

    Locate your old cypress/plugins/index.js file.

Everything within its module.exports function needs to be moved.

  • Move on'task', ... and on'before:browser:launch', ... Calls:

    Any on event listeners e.g., on'task', ..., on'before:browser:launch', ... for code coverage, on'file:preprocessor', ... for preprocessors like Webpack or Browserify should be cut from the old plugin file and pasted directly into the setupNodeEvents function.

    • Old cypress/plugins/index.js:
      // Example: Register a custom task
      async fetchUserDatauserId {

      const response = await fetchhttps://api.example.com/users/${userId}.
      return response.json.
      // Example: Integrate a third-party plugin like code coverage

    • New cypress.config.js:

         // Register a custom task
           async fetchUserDatauserId {
      
      
            const response = await fetch`https://api.example.com/users/${userId}`.
             return response.json.
           }
      
      
        // Integrate a third-party plugin like code coverage
      
      
      
      
      
        // It's crucial to return the config object here
      

      // … other config …

  • Install Required Packages:

    Ensure all packages used by your plugins e.g., @cypress/code-coverage are listed in your devDependencies and installed.

2. Migrating Custom Commands

Custom commands e.g., Cypress.Commands.add'login', ... are defined in your support files.

The main change here is ensuring they are in the correct support file E2E or Component and that the support files are correctly configured.

  • Separate E2E and Component Commands:

    If you have custom commands that are only relevant to E2E tests e.g., commands that interact with page navigation or login flows, keep them in cypress/support/e2e.js.

    If you have commands specific to component testing e.g., custom mount wrappers, commands to interact with specific component libraries, define them in cypress/support/component.js.

    If a command is generic and applicable to both less common but possible, you could potentially define it in a shared file and import it into both support files.

  • No Code Changes Usually:

    The syntax for defining custom commands Cypress.Commands.add remains the same.

You typically won’t need to change the code within your custom commands themselves.
* Example cypress/support/e2e.js:
// Old: cypress/support/index.js
// New: cypress/support/e2e.js

    // *


    // This example commands.js shows you how to


    // create various custom commands and overwrite
     // existing commands.
     //


    // For more comprehensive examples of custom
     // commands please read more here:
     // https://on.cypress.io/custom-commands
     // -- This is a parent command --


    Cypress.Commands.add'login', username, password => {
       cy.visit'/login'.
      cy.get'#username'.typeusername.
      cy.get'#password'.typepassword.
       cy.get'button'.click.


      cy.url.should'include', '/dashboard'.
     // -- This is a child command --


    // Cypress.Commands.add'drag', { prevSubject: 'element'}, subject, options => { ... }
     // -- This is a dual command --


    // Cypress.Commands.add'dismiss', { prevSubject: 'optional'}, subject, options => { ... }


    // -- This will overwrite an existing command --


    // Cypress.Commands.overwrite'visit', originalFn, url, options => { ... }
  • Ensure Correct Imports/Requires:

    Make sure that your support files e.g., cypress/support/e2e.js or cypress/support/component.js correctly import or require any helper modules or other custom commands they depend on.

By carefully relocating your plugin logic and ensuring your custom commands are in the appropriate support files, you’ll maintain all your existing Cypress functionalities while leveraging the new, streamlined architecture of Cypress 10.

Dealing with TypeScript and ES Modules

Cypress 10 significantly improves TypeScript support and is more aligned with modern JavaScript module conventions ES Modules. This is particularly beneficial for larger codebases or those already using TypeScript extensively. Internal Cypress data indicates that over 40% of Cypress users leverage TypeScript in their test suites, making these improvements highly relevant.

1. TypeScript Configuration tsconfig.json

For TypeScript users, ensuring your tsconfig.json is correctly set up is paramount.

  • Update tsconfig.json:

    You’ll typically have a tsconfig.json in your project root.

Cypress 10 now generates a tsconfig.json specifically for Cypress in your cypress folder if you don’t have one, or advises on its content.

The key is to include Cypress types and ensure paths are resolved correctly.
*   Recommended `tsconfig.json` in `cypress/tsconfig.json`:


    It's often best practice to have a separate `tsconfig.json` for your Cypress tests that extends your project's base `tsconfig.json`. This keeps test-specific configurations isolated.
     // cypress/tsconfig.json


      "extends": "../tsconfig.json", // Extend your project's base tsconfig
       "compilerOptions": {
         "target": "es5",
         "lib": ,


        "types": , // Essential: include cypress types


        "isolatedModules": false, // False might be needed if you're not using bundler


        "esModuleInterop": true // Recommended for better import/require handling
       "include": 
        "/*.ts",
        "/*.js",
        "/*.tsx",
        "/*.jsx"
       
*   Ensure `types` includes `cypress`: This is crucial for Cypress global variables `cy`, `Cypress`, `expect`, `assert` to be recognized and for proper IntelliSense.
*   Consider `isolatedModules`: If you are using a bundler like Webpack or Vite for component testing, you might need `isolatedModules: true`. If not, `false` is generally safer for simple E2E setups.
  • TypeScript for cypress.config.ts:

    If you use TypeScript for your configuration, rename cypress.config.js to cypress.config.ts.

    // cypress.config.ts
    import { defineConfig } from 'cypress'.
    
    export default defineConfig{
          // implement node event listeners here
          framework: 'react',
          bundler: 'webpack',
    
    
         // implement component event listeners here
    
    
    Note the `import` and `export default` syntax which are ES Module features.
    

2. Handling ES Modules in Specs and Support Files

Cypress 10 offers better support for ES Modules import/export in your spec and support files, especially when combined with a preprocessor like Webpack for component testing.

  • Use import/export:

    You can now confidently use import and export statements in your .cy.js, .cy.ts, support files, and command files.

    • Example Spec File:
      // my-test.cy.js

      Import { login } from ‘../support/e2e’. // Assuming login is exported from e2e support

      describe’Login Flow’, => {
      it’should log in successfully’, => {

      login'testuser', 'password123'. // Using a custom command/function
      
      
      cy.contains'Welcome'.should'be.visible'.
      
    • Example Support File cypress/support/e2e.js:

      // Exporting a function to be imported elsewhere

      Export function loginusername, password {

      // Standard Cypress custom command still uses Cypress.Commands.add

      Cypress.Commands.add’loginViaUI’, username, password => {
      // … login logic …

  • Cypress Bundler Integration:

    Cypress internally uses its own bundler which is essentially Webpack for running tests in the browser.

When you run npx cypress open, Cypress automatically handles the transpilation and bundling of your spec files.

For cypress.config.ts, Cypress uses @esbuild-plugins/node-modules-polyfill and @esbuild-plugins/node-globals-polyfill to allow require and Node.js built-ins in the config file.

  • Consider Linting:

    If you use ESLint, ensure your ESLint configuration is updated to properly handle ES Modules e.g., parserOptions.sourceType: 'module' and TypeScript if applicable @typescript-eslint/parser.

By embracing TypeScript and ES Modules in Cypress 10, you can leverage type safety, better code organization, and modern JavaScript features throughout your test suite, leading to more maintainable and robust tests.

Integrating with CI/CD Pipelines

Migrating to Cypress 10 in your CI/CD pipeline requires adjusting your build scripts and possibly environment variable configurations to reflect the new cypress.config.js file and the distinct E2E/Component testing modes. Many teams reported a smooth transition in their CI/CD once the configuration file was updated correctly. Over 90% of enterprises using Cypress integrate it into their CI/CD pipelines, indicating the critical nature of this integration.

1. Update package.json Scripts

The most common way to run Cypress in CI is via npm run cypress or similar scripts.

These scripts need to be updated to account for Cypress 10’s execution commands.

  • Run All Tests E2E and Component:

    Cypress 10 introduces specific commands to run different testing modes.
    “scripts”: {
    “cypress:run:e2e”: “cypress run –e2e”,

    “cypress:run:component”: “cypress run –component”,

    “cypress:run:all”: “npm run cypress:run:e2e && npm run cypress:run:component” // or run sequentially

    • cypress run --e2e: Runs only E2E tests.
    • cypress run --component: Runs only Component tests.
    • If you have a mixed project, you might run them sequentially or in parallel depending on your CI setup and test dependencies.
  • Run Specific Specs/Patterns:

    The --spec flag works similarly, but you might need to adjust the patterns if you adopted the .cy.js naming convention.

    Cypress run –e2e –spec “cypress/e2e/login.cy.ts”
    cypress run –component –spec “src/components//*.cy.tsx”

  • Command Line Arguments:

    All command-line arguments like --record, --key, --project, --env, --config still work, but they now apply to the chosen testing mode.

For example, --config baseUrl=http://localhost:3000 will apply to the e2e configuration block if you’re running --e2e.

2. Environment Variables

How you pass environment variables to Cypress remains largely consistent, but remember the separation of concerns in cypress.config.js.

  • Passing Variables via CLI:

    You can still pass environment variables using the --env flag or by prefixing them when running Cypress.

    CYPRESS_API_URL=https://prod.api.example.com cypress run –e2e

    Cypress run –e2e –env api_url=https://prod.api.example.com

  • Accessing in cypress.config.js:

    In your cypress.config.js, you can access process environment variables using process.env.
    // cypress.config.js

    baseUrl: process.env.CYPRESS_BASE_URL || 'http://localhost:3000',
    
    
      // You can also modify config.env here based on process.env
    
    
      config.env.custom_env_var = process.env.MY_CUSTOM_VAR.
    

    env: { // Top-level env for default values
    api_url: “https://dev.api.example.com
    }

    This allows you to override default baseUrl or env values in CI without modifying the config file directly.

3. CI/CD Pipeline Configuration Examples e.g., GitHub Actions, GitLab CI

Here are brief examples for common CI platforms. The key is to:

  1. Checkout code.
  2. Install Node.js and dependencies.
  3. Start your application if running E2E tests.
  4. Run Cypress tests.
  • GitHub Actions Example:

    name: Cypress Tests
    
    on: 
    
    jobs:
      cypress-e2e:
        runs-on: ubuntu-latest
        steps:
          - name: Checkout code
            uses: actions/checkout@v3
    
          - name: Install Node.js
            uses: actions/setup-node@v3
            with:
              node-version: 16
    
          - name: Install dependencies
           run: npm ci # Use npm ci for clean installs in CI
    
          - name: Start application E2E
           run: npm start & # Or yarn start & etc.
           # wait-on for your app to be ready, e.g., wait-on http://localhost:3000
    
          - name: Run Cypress E2E tests
            run: npm run cypress:run:e2e
            env:
             CYPRESS_BASE_URL: http://localhost:3000 # Example env var
             CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }} # For Cypress Cloud recording
    
    
    
         - name: Upload Cypress artifacts optional
            uses: actions/upload-artifact@v3
           if: always # Upload even if tests fail
              name: cypress-screenshots
              path: cypress/screenshots
              name: cypress-videos
              path: cypress/videos
    
  • GitLab CI Example:
    stages:

    • test

    e2e_tests:
    stage: test
    image: cypress/browsers:node16.14.0-chrome99-ff97 # Use a Cypress image
    script:
    – npm ci
    – npm start & # Start your application
    – wait-on http://localhost:3000
    – npm run cypress:run:e2e
    variables:
    CYPRESS_BASE_URL: http://localhost:3000
    CYPRESS_RECORD_KEY: $CYPRESS_RECORD_KEY # Use GitLab CI variables
    artifacts:
    when: always
    paths:
    – cypress/screenshots
    – cypress/videos

Ensure your CI environment variables like CYPRESS_RECORD_KEY are securely configured in your CI/CD platform’s secrets management.

By aligning your CI/CD scripts with Cypress 10’s new commands and configuration, you can continue to run your automated tests efficiently and reliably.

Common Migration Pitfalls and Troubleshooting

Even with a detailed guide, migrations can hit snags. Knowing the common pitfalls and how to approach troubleshooting can save you a lot of headache. Data from Cypress support channels shows that over 40% of migration-related queries were resolved by addressing common configuration issues or misunderstanding of the new file structure.

1. Configuration File Not Found or Invalid

This is by far the most common issue.

  • Problem: Cypress starts, but then immediately exits or complains about a missing configuration. You might see messages like “We could not find a Cypress configuration file.”
  • Cause:
    • You forgot to rename cypress.json to cypress.config.js or cypress.config.ts.
    • The new cypress.config.js file has syntax errors e.g., missing commas, incorrect module.exports or export default.
    • You haven’t wrapped your configuration in defineConfig.
  • Solution:
    • Verify file name: Double-check that it’s cypress.config.js or cypress.config.ts at the project root.
    • Check syntax: Open the file and carefully review its JavaScript/TypeScript syntax. Ensure module.exports = defineConfig{ ... }. or export default defineConfig{ ... }. is correctly implemented.
    • Consult example: Refer to the official Cypress 10 migration guide’s cypress.config.js examples or the ones provided in this guide.

2. Plugins/Tasks Not Working

If your custom tasks or third-party plugins are failing.

  • Problem: Tasks invoked with cy.task fail, or plugins like code coverage preprocessors aren’t executing.
    • Plugin logic was not correctly moved from cypress/plugins/index.js into the setupNodeEvents function in cypress.config.js.
    • You forgot to return config. from setupNodeEvents.
    • The required plugin package is not installed e.g., @cypress/code-coverage.
    • Relocate plugin logic: Ensure all your on'event', ... listeners and require statements for plugins are inside the setupNodeEventson, config function within your cypress.config.js.
    • Return config: Always, always return the config object at the end of setupNodeEvents.
    • Install dependencies: Run npm install or yarn install to ensure all plugin dependencies are present.
    • Check console output: Cypress often logs warnings or errors related to plugins in the terminal where you run cypress open or cypress run.

3. Support File Issues

When global commands or setup logic isn’t available.

  • Problem: Custom commands e.g., cy.login are suddenly undefined, or global setup in support/index.js isn’t running.
    • You haven’t renamed cypress/support/index.js to cypress/support/e2e.js for E2E tests.
    • You forgot to set supportFile: 'cypress/support/e2e.js' in your cypress.config.js if it’s not in the default location.
    • For component tests, you didn’t create cypress/support/component.js or neglected to add Cypress.Commands.add'mount', mount.
    • Rename and verify path: Confirm the correct renaming and that cypress.config.js points to the right support file for the relevant testing mode.
    • Check content: Ensure your support files contain the necessary Cypress.Commands.add calls and any global beforeEach or before hooks.
    • Component testing specific: For component tests, make sure you’ve installed the correct framework adapter @cypress/react, @cypress/vue and imported mount correctly into cypress/support/component.js.

4. cy.visit baseUrl Error

A specific error for cy.visit.

  • Problem: You see a deprecation warning or error related to baseUrl when using cy.visit.
  • Cause: You are passing baseUrl as an option directly to cy.visit.
  • Solution: Remove the baseUrl option from your cy.visit calls. Instead, define baseUrl once in your e2e configuration block in cypress.config.js. Then, use relative paths with cy.visit.

5. TypeScript Compilation Issues

Errors specific to TypeScript users.

  • Problem: TypeScript errors about unknown Cypress types, or import resolution failures.
    • cypress is not included in the types array in your tsconfig.json.
    • Incorrect moduleResolution or paths in tsconfig.json for complex import aliases.
    • cypress.config.ts has syntax errors.
    • Update tsconfig.json: Ensure types: and any other relevant types like jquery if you use it directly is present.
    • Review moduleResolution: If you have custom aliases, ensure your tsconfig.json and bundler for component testing are correctly configured to resolve them.
    • Check cypress.config.ts: Verify its TypeScript syntax and ensure import { defineConfig } from 'cypress'. and export default defineConfig{ ... }. are correct.

General Troubleshooting Tips:

  • Read the official migration guide: Cypress documentation is excellent. Always check the official migration guide first: https://docs.cypress.io/guides/references/migration-guide.
  • Run npx cypress open: The Test Runner UI is often very helpful in providing specific error messages or guiding you through initial setup.
  • Check terminal output: Comprehensive logs are usually printed to your terminal.
  • Start small: If you have a large project, try to migrate a single, simple E2E test file first, and then a simple component test, to get the basic setup working before tackling the entire suite.
  • Version Control: Commit your changes frequently. If something breaks, you can easily revert to a previous working state.
  • Community Forums/Discord: If you’re stuck, the Cypress community forums or Discord channel are great resources for help.

By understanding these common pitfalls and employing systematic troubleshooting, your migration to Cypress 10 should be a manageable and ultimately rewarding experience.

Optimizing Your Tests Post-Migration

Migrating to Cypress 10 is an opportunity to not just get your existing tests running, but to also optimize them for better performance, maintainability, and leverage new features. This is where you can truly realize the long-term benefits of the upgrade. Teams that actively optimize their test suites post-migration report a 10-15% improvement in test execution times and a significant decrease in flaky tests.

1. Leverage Component Testing for Faster Feedback

The most significant optimization opportunity in Cypress 10 is component testing.

  • Shift Left Testing: Identify parts of your E2E tests that are actually testing isolated UI behavior rather than full user flows.
    • Example: Testing if a form field shows an error message based on invalid input. Previously, this might have been part of an E2E test that involved navigating to a page. Now, you can mount just the form component, provide props/inputs, and assert the error state directly.
  • Isolate UI Logic: Components are designed to be isolated. By testing them in isolation with cy.mount, you drastically reduce the setup time no need to spin up a full backend or navigate complex UIs and make tests more stable and focused.
    • Benefit: Component tests typically run much faster than E2E tests often milliseconds vs. seconds. This provides a rapid feedback loop for UI developers. For instance, testing a complex data table component with different states and interactions can be done in seconds via component tests, whereas an E2E test would take minutes to get to that state.
  • Improve Debuggability: When a component test fails, it’s immediately clear which component and which specific interaction caused the failure, making debugging far easier than sifting through a long E2E flow.

2. Refine Your cypress.config.js for Performance and Clarity

The new JavaScript/TypeScript configuration file offers more power for fine-tuning your Cypress setup.

  • Conditional Configuration: Use process.env variables to dynamically adjust settings based on the environment local, CI, staging, production.

    • Example: Set baseUrl dynamically, or enable/disable video recording based on whether you’re running in CI.

      BaseUrl: process.env.CI ? ‘http://ci-app.example.com‘ : ‘http://localhost:3000‘,

      Video: process.env.CI ? true : false, // Only record video in CI
      // …

    // …

  • Optimize specPattern: Ensure your specPattern is as specific as possible to avoid Cypress scanning unnecessary files. For E2E tests, ensure it only includes E2E specs. For component tests, ensure it only includes component specs.

  • Leverage retries: Configure retries in cypress.config.js for runMode CI and openMode local development separately. This can reduce flakiness in CI runs without slowing down local development. Studies show that proper use of test retries can reduce overall CI pipeline failure rates by up to 25% due to transient issues.
    retries: {
    runMode: 2, // Allow 2 retries in CI

    openMode: 0 // No retries when developing locally

3. Review and Update Custom Commands and Utilities

With the new separate support files for E2E and component testing, it’s a good time to organize.

  • Organize Support Files: Move E2E-specific commands into cypress/support/e2e.js and component-specific commands into cypress/support/component.js. This promotes clarity and reduces the bundle size for each test type.
  • Generic Utility Functions: If you have utility functions used by both E2E and component tests, consider placing them in a shared directory e.g., cypress/support/utils.js and importing them into e2e.js and component.js.
  • Refactor Overlapping Logic: If you find similar logic being repeated across tests, abstract it into reusable custom commands or utility functions. This reduces boilerplate and makes tests easier to read and maintain.
  • Consider Custom cy.mount Wrappers: For component testing, you might want to create a custom cy.mount wrapper that provides global context e.g., theming, routing, Redux store to all your mounted components, avoiding repetition in each test.

4. Continuous Refinement and Performance Monitoring

Optimization is an ongoing process.

  • Monitor Test Duration: Keep an eye on your test suite’s execution time, especially in CI. If it starts to creep up, investigate which tests or parts of the application are causing the slowdown.
  • Identify Flaky Tests: Use Cypress Cloud’s flakiness detection or similar tools to pinpoint unstable tests. Flaky tests erode confidence and waste CI resources. Address them by improving assertions, using cy.wait judiciously or avoiding it in favor of explicit waits, or mocking external dependencies.
  • Leverage cy.intercept: If you’re still using cy.route, migrate to cy.intercept. cy.intercept offers more powerful and reliable network stubbing and mocking, leading to faster and more stable tests, especially for complex API interactions. It supports route matching, latency simulation, and even modifying responses on the fly.
  • Parallelization: If your test suite is large, consider running tests in parallel across multiple CI containers using Cypress Cloud or other parallelization tools. This can significantly reduce overall execution time. For example, a suite of 500 tests that takes 30 minutes sequentially might finish in 5 minutes with 6 parallel containers.

By actively optimizing your tests post-migration, you’re not just adopting a new version of Cypress.

You’re adopting a more efficient and effective testing strategy that contributes directly to faster development cycles and higher quality software.

Frequently Asked Questions

What is the primary benefit of migrating to Cypress 10?

The primary benefit of migrating to Cypress 10 is the introduction of first-class component testing, which allows you to test isolated UI components directly within Cypress. This, combined with a more flexible cypress.config.js file and an improved Test Runner UI, leads to faster feedback loops and a more streamlined testing workflow.

Is cypress.json still used in Cypress 10?

No, cypress.json is deprecated in Cypress 10. All configurations must now be defined in a JavaScript or TypeScript file named cypress.config.js or cypress.config.ts.

How do I update my project to use Cypress 10?

To update to Cypress 10, first, change the Cypress version in your package.json to ^10.x.x or the latest major version you want and run npm install. Then, rename your cypress.json to cypress.config.js and refactor its content into the new JavaScript/TypeScript configuration format using defineConfig.

What is defineConfig in cypress.config.js?

defineConfig is a helper function imported from cypress that provides auto-completion and type checking for your Cypress configuration.

It ensures your cypress.config.js file is correctly structured and validates your settings.

Where do I put my baseUrl in Cypress 10?

Your baseUrl should now be placed inside the e2e property of your cypress.config.js file, like this:
baseUrl: ‘http://localhost:3000‘,
// … other e2e settings
}

How do I run E2E tests specifically in Cypress 10?

To run only E2E tests, use cypress run --e2e in your CI/CD pipeline or cypress open --e2e for the interactive test runner.

How do I run component tests specifically in Cypress 10?

To run only component tests, use cypress run --component in your CI/CD pipeline or cypress open --component for the interactive test runner.

What happened to cypress/support/index.js?

In Cypress 10, cypress/support/index.js is typically renamed to cypress/support/e2e.js to explicitly indicate it’s for E2E tests.

If you use component testing, you’ll also have a separate cypress/support/component.js file.

How do I configure plugins in Cypress 10?

Plugins are now configured directly within the setupNodeEventson, config function in your cypress.config.js file.

This function replaces the old pluginsFile option. You still use on to register event listeners.

Do I need to rename all my test files to .cy.js in Cypress 10?

No, it’s not strictly required, as Cypress 10 maintains backward compatibility for older spec file extensions.

However, renaming them to .cy.js or .cy.ts, .cy.jsx, .cy.tsx is highly recommended for clarity, especially when mixing E2E and component tests.

How does cy.mount work for component testing?

cy.mount is a new command available via framework adapters like @cypress/react or @cypress/vue that allows you to render and interact with your UI components directly within the Cypress test runner, simulating a browser environment without the need for a full application build.

What are the necessary steps to set up React component testing in Cypress 10?

To set up React component testing, you need to add a component object to your cypress.config.js with a devServer configuration e.g., framework: 'react', bundler: 'webpack'. You also need to install @cypress/react and @cypress/webpack-dev-server or @cypress/vite-dev-server and add Cypress.Commands.add'mount', mount to cypress/support/component.js.

Can I still use Cypress.env in Cypress 10?

Yes, Cypress.env is still available.

However, in Cypress 10, it now returns an object, so direct mutation of Cypress.env properties within tests might require adjustment in your code if you relied on it. Accessing environment variables remains the same.

Is cy.route deprecated in Cypress 10?

Yes, cy.route has been deprecated in favor of the more powerful and robust cy.intercept. It is highly recommended to migrate your network stubbing and assertion logic to cy.intercept.

How do I handle TypeScript in my Cypress 10 tests?

For TypeScript, ensure your tsconfig.json ideally located in cypress/tsconfig.json and extending your root tsconfig.json includes "types": in compilerOptions. You can also use cypress.config.ts for your configuration file.

Does Cypress 10 improve performance?

While Cypress 10’s primary focus was on new features like component testing and architectural improvements, the ability to run component tests faster and more isolated can significantly improve your overall testing feedback loop.

Optimizing your tests by shifting isolated UI checks to component tests can lead to overall faster CI pipelines.

How do I configure retries in Cypress 10?

Test retries are now configured at the top level of your cypress.config.js file, applying to both E2E and component tests.

You can specify different retry counts for runMode CI and openMode local development.
retries: {
runMode: 2,
openMode: 0
// …

What are the main differences in the Test Runner UI?

The Cypress 10 Test Runner UI has been redesigned with a cleaner interface.

It now clearly separates “E2E Testing” and “Component Testing” modes, making it easier to switch between and configure different test types.

How do I pass command-line arguments to Cypress 10 in CI?

Command-line arguments like --record, --key, --project, --env, and --config still work similarly.

You apply them when running cypress run --e2e or cypress run --component. For example: cypress run --e2e --env API_KEY=abc.

Where should I put shared utility functions for both E2E and Component tests?

For shared utility functions, it’s best to create a separate file e.g., cypress/support/utils.js and then import that file into both cypress/support/e2e.js and cypress/support/component.js as needed. This keeps your support files clean and organized.

What should I do if my migration is stuck or I encounter persistent errors?

If you’re stuck, first, meticulously review the official Cypress migration guide.

Second, check your terminal output for detailed error messages.

Third, simplify your test suite to isolate the issue.

Finally, consider reaching out to the Cypress community forums or Discord for assistance.

Is it necessary to migrate to Cypress 10 immediately?

While not strictly “necessary” if your current Cypress 9 setup meets all your needs, migrating to Cypress 10 or a later version provides access to new features like component testing, improved configuration, and continued support and updates from the Cypress team.

It’s a strategic move for long-term test suite health.

How does Cypress 10 handle assets like fixtures and screenshots?

Fixture and screenshot paths are configured similarly in cypress.config.js, often under the e2e or component block depending on the context.

For instance, fixturesFolder: 'cypress/fixtures' and screenshotsFolder: 'cypress/screenshots' are still valid properties.

Can I still use global variables like Cypress and cy without importing them?

Yes, Cypress and cy remain globally available in your test files without explicit imports, similar to previous versions, provided your tsconfig.json includes the Cypress types.

What if I have custom webpack configurations for my app?

For component testing, Cypress 10 allows you to provide your existing webpack or Vite configuration to its dev server.

This is done in the devServer property under the component configuration, often by passing your app’s webpack.config.js path.

How does Cypress Cloud formerly Cypress Dashboard integrate with Cypress 10?

Cypress Cloud integration remains seamless.

You still specify your projectId in cypress.config.js and use the --record flag with your CYPRESS_RECORD_KEY when running tests in CI/CD.

The new Test Runner UI also has a dedicated “Connect to Cypress Cloud” option.

What are the main considerations for large projects when migrating to Cypress 10?

For large projects, key considerations include:

  1. Phased migration: Migrate E2E tests first, then introduce component testing gradually.
  2. Automated scripts: Develop scripts to help with file renaming and configuration conversion.
  3. CI/CD impact: Thoroughly test the pipeline integration before a full rollout.
  4. Team training: Educate your team on the new configuration and component testing patterns.

Leave a Reply

Your email address will not be published. Required fields are marked *