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
-
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. -
Initialize Cypress. Run
npx cypress opento launch the Cypress Test Runner. It will create acypress/folder with default configurations and example specs. Close the runner after initialization. -
Configure Cypress for Angular. Edit the generated
cypress.config.tsfile. SetbaseUrlto your Angular dev server URL (e.g.,http://localhost:4200). If you use Angular’s proxy, adjust accordingly. Also, add thecypress-angularplugin if you need to interact with Angular-specific features like component testing. For E2E, the default setup is sufficient. -
Set up TypeScript support. Ensure your
tsconfig.jsonincludes"types": ["cypress"]in the compilerOptions. This gives you IntelliSense for Cypress commands. If you have a separate tsconfig for Cypress, add it there. -
Map Protractor locators to Cypress. Protractor uses
by.css,by.xpath, etc. Cypress uses jQuery-style selectors. For example:element(by.css('.btn-primary'))becomescy.get('.btn-primary')element(by.id('username'))becomescy.get('#username')element(by.buttonText('Submit'))becomescy.contains('button', 'Submit')
-
Replace Protractor actions. Protractor’s
sendKeys,click, andgetTextmap 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')
-
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 withcy.wait(ms)only when necessary. For Angular-specific synchronization, consider using thecypress-angularplugin or write custom commands to wait for Angular’s stability. -
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'); }); }); -
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, usecy.intercept()to wait for API calls before asserting. -
Run and debug. Execute
npx cypress runto run all tests headlessly. Usenpx cypress opento debug interactively. Cypress’s time-travel debugging and screenshots make failures easier to diagnose. -
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 yourpackage.jsonscripts 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.bindingorby.modelhave 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 --recordto get dashboards and video recordings. - Migrate test by test, not all at once, to maintain coverage during the transition.
- Use
cy.clock()andcy.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 yourbaseUrlmatches 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 withcy.scrollIntoView(). - Network requests hang. Use
cy.intercept()to stub or wait for specific requests. You can also log requests withcy.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
- How to Check Your Linux Kernel for Spectre
- iPhone Safe Mode: How to Enable or Disable It
- Fix Slow Internet Lag on Samsung Galaxy Note
- iOS 18 Safari Not Working? Fixes That Help
- How to Get iOS 17 on iPhone X (Safe Methods)
- Fix Gmail IMAP Error in Outlook: Step-by-Step