Narrowing Down Protractor Test Execution with Angular CLI

Running end-to-end suites can be time-consuming, and as the number of tests grows, the ability to execute a targeted subset becomes increasingly important.

Starting with Angular CLI 9.1, the Protractor builder supports the --grep and --invert-grep flags. These options allow developers to filter which tests are executed by forwarding the filtering logic directly to Protractor.

ng e2e my-app --grep "logged out"
Enter fullscreen mode Exit fullscreen mode

The example above shows a basic usage of the filter. The grep value is treated as a regular expression, meaning any test whose description contains "logged out" will be included in the run. This applies to descriptions supplied through both the describe and it wrapper functions.

When you need to exclude matching tests, the --invert-grep flag can be applied to reverse the matching logic, as illustrated below.

ng e2e my-app --grep "logged out" --invert-grep
Enter fullscreen mode Exit fullscreen mode

The grep option interprets the provided expression as a regex and evaluates it against the fully concatenated test description, combining all parent and child description segments. For instance, a fresh Angular CLI workspace scaffolds a default end-to-end spec that resembles the following structure.

import { AppPage } from './app.po';

describe('workspace-project App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getTitleText()).toEqual('my-app app is running!');
  });
});
Enter fullscreen mode Exit fullscreen mode

In this scenario, the full test description reads "workspace-project App should display welcome message". To isolate this particular test, you could use "^workspace" or "message$" as the grep value. A more complex pattern, such as the one in the following command, would match tests that begin with "workspace" or conclude with "message".

ng e2e my-app --grep "^workspace|message$"
Enter fullscreen mode Exit fullscreen mode

While Protractor itself has recognized the grep and invertGrep parameters for a long time, native support for these flags within the Angular CLI's official Protractor builder only became available in version 9.1.