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
- Install Protractor globally and locally. Run
npm install -g protractorto install the CLI globally. Then, in your project directory, runnpm install --save-dev protractorto add it as a dev dependency. This ensures the correct version is used in your project. - Update WebDriver. Protractor uses Selenium WebDriver to control browsers. Run
webdriver-manager updateto download the necessary drivers (ChromeDriver for Chrome, geckodriver for Firefox). This command is available after the global install. - 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. - 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
specspath andbaseUrlto match your project. - Write your first test spec. Create a directory
e2e(or wherever you pointedspecs) and add a file likeapp.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
browserandelementglobals are available automatically. - Run the test. Start your Angular development server (e.g.,
ng serve) in a separate terminal. Then runprotractor protractor.conf.jsfrom your project root. Protractor will open Chrome, navigate to your app, and execute the test. - Use Angular-specific locators. Protractor provides locators like
by.model,by.binding, andby.repeaterthat 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.
- 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); - 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); - 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
LoginPageclass with methods likelogin(username, password). - 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
--headlessflag 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, orby.cssContainingTextinstead. - 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
awaitin async functions consistently, or use the olderthen()chains. Mixing can lead to flaky tests. - Hard-coding waits. Using
browser.sleep()to wait for conditions is fragile. Usebrowser.wait()with expected conditions instead.
Tips
- Use
browser.ignoreSynchronizationfor non-Angular pages. If you test a page that is not Angular (e.g., a login page from a third-party), setbrowser.ignoreSynchronization = true(orwaitForAngularEnabled(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
beforeEachto set up state, and avoid relying on test order. - Use
protractorCLI options. For example,--suiteto run specific test suites, or--paramsto 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_VERSIONor 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 useelement.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-managerconfig. - Tests pass locally but fail in CI. CI environments may have different screen resolutions or lack a display. Use headless Chrome and set
--window-sizein 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
- Fix Text Cursor Turning White in Windows 11
- Force Quit Non-Responding Apps on Mac: 6 Ways
- Chromebook Not Charging? Fix It Fast
- iPhone Won’t Make Calls but Texts Work? Fixes
- Android to iPhone Hotspot: Connect & Fix Issues
- How to Refresh or Factory Reset Your Microsoft Surface