sodcalculator

10 Tech How-To

Protractor Testing Angular: Step-by-Step Guide

Guide 10-52506 · Updated · Step by step

This guide walks you through using Protractor, an end-to-end testing framework built specifically for Angular and AngularJS applications. You’ll learn how to set up Protractor, write tests that interact with your app’s UI, and run them against a live development server. By the end, you’ll have a working test suite that verifies your Angular components behave as expected in a real browser.

What You’ll Need

  • Node.js (v18 or later recommended) and npm installed on your machine.
  • An existing Angular project (Angular 2+ or AngularJS 1.x) with its dependencies installed.
  • A basic understanding of TypeScript/JavaScript and the command line.
  • Google Chrome installed (Protractor uses ChromeDriver by default, though you can configure other browsers).

Step-by-Step

  1. Install Protractor globally and locally. Run npm install -g protractor to install the CLI globally. Then, in your project directory, run npm install --save-dev protractor to add it as a dev dependency. This ensures the correct version is used in your project.
  2. Update WebDriver. Protractor uses Selenium WebDriver to control browsers. Run webdriver-manager update to download the necessary drivers (ChromeDriver for Chrome, geckodriver for Firefox). This command is available after the global install.
  3. Start WebDriver (optional). For local testing, you can start a Selenium Server with webdriver-manager start. However, Protractor can also run directly against ChromeDriver without the standalone server, which is faster for most projects.
  4. Create a Protractor configuration file. In your project root, create protractor.conf.js. This file tells Protractor where your tests are, the URL of your app, and how to connect to the browser. A minimal config looks like:
    exports.config = {
      framework: 'jasmine',
      specs: ['e2e/**/*.spec.js'],
      capabilities: {
        browserName: 'chrome'
      },
      baseUrl: 'http://localhost:4200'
    };

    Adjust the specs path and baseUrl to match your project.

  5. Write your first test spec. Create a directory e2e (or wherever you pointed specs) and add a file like app.spec.js. Start with a simple test that loads your app and checks a heading:
    describe('My Angular App', () => {
      it('should display the title', async () => {
        await browser.get('/');
        const heading = element(by.css('h1'));
        expect(await heading.getText()).toBe('Welcome');
      });
    });

    Protractor’s browser and element globals are available automatically.

  6. Run the test. Start your Angular development server (e.g., ng serve) in a separate terminal. Then run protractor protractor.conf.js from your project root. Protractor will open Chrome, navigate to your app, and execute the test.
  7. Use Angular-specific locators. Protractor provides locators like by.model, by.binding, and by.repeater that work with Angular’s data binding. For example, to find an input bound to a model property:
    const nameInput = element(by.model('user.name'));
    await nameInput.sendKeys('Alice');

    These locators are more robust than CSS selectors because they rely on Angular’s internal metadata.

  8. Handle asynchronous operations. Protractor automatically waits for Angular’s digest cycle to settle before performing actions, so you don’t need explicit waits for most cases. However, for external HTTP requests or timeouts, use browser.wait() with expected conditions:
    const EC = protractor.ExpectedConditions;
    await browser.wait(EC.visibilityOf(element(by.id('result'))), 5000);
  9. Test user interactions. Simulate clicks, typing, and other events using Protractor’s element actions. For example, to submit a form:
    await element(by.buttonText('Submit')).click();
    const successMsg = element(by.css('.alert-success'));
    expect(await successMsg.isDisplayed()).toBe(true);
  10. Organize tests with page objects. For larger applications, create page object classes that encapsulate selectors and actions for each page. This reduces duplication and makes tests easier to maintain. For example, a LoginPage class with methods like login(username, password).
  11. Run tests in CI (optional). In your CI pipeline, you can start the web server, run Protractor with Chrome headless, and then shut down. Use the --headless flag in Chrome capabilities to run without a GUI.

Common Mistakes

  • Not waiting for Angular to load. If your app uses external resources, Protractor may try to interact before the page is fully ready. Use browser.waitForAngularEnabled(true) (default) and ensure your test waits for specific elements when needed.
  • Using CSS selectors for Angular-specific elements. Avoid relying on generated CSS classes or DOM structure; use by.model, by.binding, or by.cssContainingText instead.
  • Forgetting to start the dev server. Protractor does not build or serve your app; you must have it running at the baseUrl.
  • Mixing sync and async code. Protractor’s API is promise-based. Use await in async functions consistently, or use the older then() chains. Mixing can lead to flaky tests.
  • Hard-coding waits. Using browser.sleep() to wait for conditions is fragile. Use browser.wait() with expected conditions instead.

Tips

  • Use browser.ignoreSynchronization for non-Angular pages. If you test a page that is not Angular (e.g., a login page from a third-party), set browser.ignoreSynchronization = true (or waitForAngularEnabled(false) in newer versions) to avoid timeouts.
  • Run tests in a separate environment. Use a test database or mock APIs to avoid affecting production data.
  • Take screenshots on failure. Add a Jasmine reporter that captures screenshots when a test fails. This helps debug issues quickly.
  • Keep tests independent. Each test should be able to run in isolation. Use beforeEach to set up state, and avoid relying on test order.
  • Use protractor CLI options. For example, --suite to run specific test suites, or --params to pass custom parameters.

Troubleshooting

  • ChromeDriver version mismatch. If you get an error about ChromeDriver not supporting your Chrome version, run webdriver-manager update --versions.chrome=YOUR_VERSION or update Chrome to the latest stable.
  • Timeout waiting for Angular. This often happens when the app has continuous async activity (e.g., polling). You can disable waiting for Angular on specific pages with await browser.waitForAngularEnabled(false) before navigation, then re-enable it.
  • Element not found. Ensure your selectors are correct. Use browser.pause() to pause the test and inspect the page in the browser console. You can also use element.all(by.css(...)).count() to debug.
  • Port already in use. If WebDriver cannot start, kill any existing Java processes or change the port in webdriver-manager config.
  • Tests pass locally but fail in CI. CI environments may have different screen resolutions or lack a display. Use headless Chrome and set --window-size in capabilities.

Frequently Asked Questions

Can I use Protractor with Angular 2+?

Yes, Protractor was originally built for AngularJS, but it works with Angular 2 and later versions. It uses the same APIs, and Angular’s CLI even includes Protractor by default.

How do I test a component that makes HTTP calls?

You can use browser.waitForAngular to wait for Angular’s HTTP requests to complete. For external calls, mock them using a library like angular-mocks or intercept with browser.addMockModule.

What is the difference between Protractor and Karma?

Karma is a unit testing runner that runs tests in a browser with mocked dependencies. Protractor runs end-to-end tests against a real, running application, interacting with the UI as a user would.

Can I test non-Angular pages with Protractor?

Yes, but you need to disable Angular synchronization for those pages using browser.waitForAngularEnabled(false). This is common for login pages hosted on a different domain.

How do I run only a specific test?

Use Jasmine’s fit (focused test) or fdescribe (focused describe) to run only that test. Alternatively, use the --specs CLI option to specify a file.

Is Protractor still maintained?

Protractor is in maintenance mode; the Angular team recommends using Cypress or Playwright for new projects. However, Protractor is still widely used and works for existing projects.

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 →