sodcalculator

10 Tech How-To

Migrate Protractor Tests to Cypress: Step-by-Step

Guide 10-45924 · Updated · Step by step

Migrating Protractor tests to Cypress for an Angular app modernizes your end-to-end testing, offering faster execution, a more intuitive API, and built-in waiting. This guide walks you through the process, from setting up Cypress to rewriting your specs and handling Angular-specific quirks. You’ll need your existing Protractor suite, an Angular app, and basic familiarity with TypeScript and testing concepts.

What You’ll Need

  • An Angular application (v12 or later recommended) with existing Protractor tests.
  • Node.js (v18 or later) and npm installed.
  • Access to the terminal or command line.
  • A code editor (VS Code or similar).

Step-by-Step

  1. Install Cypress. In your project root, run:

    npm install -D cypress

    This adds Cypress as a dev dependency. If you use Yarn, run yarn add -D cypress.

  2. Initialize Cypress. Run npx cypress open to launch the Cypress Test Runner. It will create a cypress/ folder with default configurations and example specs. Close the runner after initialization.
  3. Configure Cypress for Angular. Edit the generated cypress.config.ts file. Set baseUrl to your Angular dev server URL (e.g., http://localhost:4200). If you use Angular’s proxy, adjust accordingly. Also, add the cypress-angular plugin if you need to interact with Angular-specific features like component testing. For E2E, the default setup is sufficient.
  4. Set up TypeScript support. Ensure your tsconfig.json includes "types": ["cypress"] in the compilerOptions. This gives you IntelliSense for Cypress commands. If you have a separate tsconfig for Cypress, add it there.
  5. Map Protractor locators to Cypress. Protractor uses by.css, by.xpath, etc. Cypress uses jQuery-style selectors. For example:

    • element(by.css('.btn-primary')) becomes cy.get('.btn-primary')
    • element(by.id('username')) becomes cy.get('#username')
    • element(by.buttonText('Submit')) becomes cy.contains('button', 'Submit')
  6. Replace Protractor actions. Protractor’s sendKeys, click, and getText map directly to Cypress commands:

    • element.sendKeys('text') → cy.get('input').type('text')
    • element.click() → cy.get('button').click()
    • element.getText() → cy.get('div').invoke('text')
  7. Handle waiting and synchronization. Protractor automatically waits for Angular to settle. Cypress does not wait for Angular by default. Use cy.intercept() to wait for network requests, or add explicit waits with cy.wait(ms) only when necessary. For Angular-specific synchronization, consider using the cypress-angular plugin or write custom commands to wait for Angular’s stability.
  8. Rewrite your test specs. Create new spec files in cypress/e2e/. For each Protractor spec, translate the logic. Example:

    // Protractor
    describe('Login', () => {
      it('should log in', () => {
        browser.get('/login');
        element(by.id('email')).sendKeys('test@example.com');
        element(by.id('password')).sendKeys('password');
        element(by.buttonText('Sign in')).click();
        expect(browser.getCurrentUrl()).toContain('/dashboard');
      });
    });
    
    // Cypress
    describe('Login', () => {
      it('should log in', () => {
        cy.visit('/login');
        cy.get('#email').type('test@example.com');
        cy.get('#password').type('password');
        cy.contains('button', 'Sign in').click();
        cy.url().should('include', '/dashboard');
      });
    });
        
  9. Handle Angular-specific features. For things like ng-model, use cy.get('[ng-model="username"]'). For *ngIf elements, they are present in the DOM when visible, so Cypress’s default retry-ability works. For async operations, use cy.intercept() to wait for API calls before asserting.
  10. Run and debug. Execute npx cypress run to run all tests headlessly. Use npx cypress open to debug interactively. Cypress’s time-travel debugging and screenshots make failures easier to diagnose.
  11. Remove Protractor. Once all specs are migrated and passing, uninstall Protractor and its dependencies: npm uninstall protractor. Also remove any Protractor config files (e.g., protractor.conf.js) and update your package.json scripts to use Cypress.

Common Mistakes

  • Using Protractor’s implicit waits. Cypress does not wait for Angular, so tests may fail if you don’t handle asynchronous operations. Always use cy.intercept() or explicit assertions.
  • Ignoring Cypress’s retry-ability. Cypress automatically retries commands until they pass or time out. Avoid adding unnecessary cy.wait() which slows tests and can cause flakiness.
  • Not updating selectors. Protractor’s by.binding or by.model have no direct Cypress equivalent. Use CSS classes, IDs, or data attributes instead.
  • Forgetting to handle pop-ups and alerts. Cypress handles native dialogs differently. Use cy.on('window:alert', ...) to stub or assert alerts.
  • Keeping Protractor config files. Leaving old config can cause confusion. Clean up thoroughly.

Tips

  • Use data-testid attributes on your elements to make selectors robust and independent of styling.
  • Leverage Cypress custom commands to encapsulate repeated actions, like login or navigation.
  • Run Cypress in CI with npx cypress run --record to get dashboards and video recordings.
  • Migrate test by test, not all at once, to maintain coverage during the transition.
  • Use cy.clock() and cy.tick() to control time-dependent features like debounced inputs.

Troubleshooting

  • Tests fail with “Cypress detected a cross-origin error.” This often happens when your app redirects to a different domain. Use cy.origin() to handle cross-origin requests, or ensure your baseUrl matches the app’s domain.
  • Angular app doesn’t load. Check that your dev server is running and accessible at baseUrl. If using a proxy, ensure Cypress is configured to use it.
  • Elements are not visible. Cypress requires elements to be visible to interact. Use cy.get().should('be.visible') to wait, or scroll into view with cy.scrollIntoView().
  • Network requests hang. Use cy.intercept() to stub or wait for specific requests. You can also log requests with cy.intercept('*', (req) => console.log(req.url)) to debug.
  • TypeScript errors in Cypress specs. Ensure your tsconfig includes Cypress types and that your Cypress specs are included in compilation. You may need to create a separate tsconfig.cypress.json.

Frequently Asked Questions

Can I use Protractor and Cypress simultaneously?

Yes, you can run both during migration. Keep Protractor specs in their original location and add Cypress specs in cypress/e2e/. Just ensure both test runners don’t interfere with each other.

Does Cypress support Angular’s async operations?

Cypress does not automatically wait for Angular’s change detection. You need to use cy.intercept() to wait for HTTP responses, or use the cypress-angular plugin for better synchronization.

How do I handle file uploads in Cypress?

Use cy.get('input[type=file]').attachFile('path/to/file') with the cypress-file-upload plugin, or use cy.fixture() to provide test data.

Can I reuse my Protractor page objects in Cypress?

Yes, but you’ll need to rewrite them. Convert Protractor’s ElementFinder methods to Cypress commands. You can create Cypress custom commands that wrap your page object functions.

What about Angular Material components?

Cypress works with Angular Material, but you may need to use more specific selectors. For example, to select a mat-select option, use cy.get('mat-select').click().get('mat-option').contains('Option 1').click().

Is Cypress faster than Protractor?

Generally, yes. Cypress runs in the browser and doesn’t require a Selenium server, which reduces overhead. Tests also run in parallel by default in CI.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →