07 Apr 2020
2 min

Spectator – when testing becomes a pleasure

Angular is a nice framework, isn't it? ? But like every tool, it has its weaknesses. A definite shortcoming is, for example, writing integration tests for templates and component classes. The TestBed testing module provided is simply unpleasant.  Can we safely say that such basic things as:

  • mocking up the component dependencies
  • access to a rich set of assertions (only basic ones from Jasmine)
  • catching elements (fixture.debugElement, brrr!!)
  • simple test cases, e.g. if "is button disabled"

Are they simple and clear? For me… definitely not! And at this point, it comes in all white:

spectator

The spectator is a pretty thoughtful abstraction on the built-in angular testing module. The main author is Netanel Basal, who also runs an angular blog – https://netbasal.com, highly recommended! The library makes test writing, readability, and maintenance significantly easier.

The main advantages of the library:

  • support for testing pipes, components, directives, HTTP services and routing
  • simplified catching of DOM tree elements (like in jQuery?)
  • richer API for running events (Mouse helpers and Keyboard helpers)
  • comfortable testing with HostComponent
  • support for ng-content testing
  • more matchers, such as .toBeDisabled() or .toBeFocused()
  • support for entry components and component providers
  • service auto-location, wow!
  • support for IS
  • global queries:
const element = spectator.query('.overlay', {
  root: true,
})

Let’s check it!

Let's compare what the test elements in Spectator might look like compared to the TestBed Module, with simple examples.

  1. Disabled button status:
 // SPECTATOR
  expect(spectator.query('.button')).toBeDisabled();

  // TEST BED
  const button = fixture.debugElement.query(By.css('.button'));
  expect(button.nativeElement.disabled).toBeTruthy();

2. Does *ngFor display 2 components in a list:

  // SPECTATOR
  expect('app-tshirt-item').toHaveLength(2);

  // TEST BED
  const items = fixture.debugElement.queryAll(By.directive(TshirtItemComponent));
  expect(items.length).toBe(2);

3. Locking the service as a component dependency:

// SPECTATOR
  providers: [mockProvider(AuthService)], // mockProvider ze Spectator

  // TEST BED
  providers: [
    {
      provide: AuthService,
      useClass: MockAuthService, // nasza zamockowana klasa
    },
  ]

4. Calling "enter" on input:

 // SPECTATOR
  const input = spectator.query('input');
  spectator.keyboard.pressEnter(input);

  // TEST BED
  const input = fixture.debugElement.query(By.css('input'));
  input.triggerEventHandler('keydown.enter', {});

5. Whether the element contains the text:

// SPECTATOR
const title = spectator.query('h1');
expect(title).toContainText('Page title');

// TEST BED
const title = fixture.debugElement.query(By.css('h1'));
expect(title.nativeElement.textContent).toContain('Page title');

There is no denying that it looks much simpler and clearer in Spectator! You will find dozens of examples in the documentation: https://github.com/ngneat/spectator.

Installation

If I've convinced you of Spectator, there's nothing left to do but add it to your project along with ng-mocks via npm:

npm i -D @netbasal/spectator ng-mocks

Schematics

It is also worth mentioning that Spectator has its Schematics. For example, to generate a test file for a component, we can use the command:

ng g cs path/component-name

Bonus!

If you code using Visual Studio Code, be sure to add the snippet plugin:

Practice with a playground from the authors:

PLAYGROUND

Enjoy testing! ?

Frequently asked questions

What is Spectator in Angular, and why use it for testing?

Spectator is an abstraction over Angular’s built-in testing module that makes component and template tests simpler to write and read. It provides concise DOM queries, event helpers, and additional matchers such as toBeDisabled() and toBeFocused(). It also supports testing pipes, directives, HTTP services, routing, host components, and ng-content.

How do I install Spectator in an Angular project?

Install Spectator and ng-mocks as development dependencies with npm i -D @netbasal/spectator ng-mocks. Spectator also provides schematics for generating test files; the article gives ng g cs path/component-name as an example for a component. The project’s documentation contains further examples.

How is Spectator different from Angular TestBed in component tests?

Spectator offers a more concise API for common component-test tasks than writing directly with Angular’s TestBed and fixture.debugElement. For example, a disabled-button check can use spectator.query('.button') and toBeDisabled(), instead of querying through By.css and checking the native element’s disabled property. Both approaches test the component; Spectator reduces the setup and querying code.

How do I mock a service dependency with Spectator?

Add mockProvider(AuthService) to the component test’s providers configuration to mock an AuthService dependency with Spectator. With plain TestBed, the example instead registers the service using provide: AuthService and useClass: MockAuthService. Spectator’s helper avoids having to specify that manual provider mapping in this example.

How do I query elements and trigger keyboard events with Spectator?

Use spectator.query() to find an element, then use Spectator’s keyboard helpers to trigger interactions; for example, spectator.keyboard.pressEnter(input) presses Enter on an input. The article also shows checking element text with toContainText() and counting matching elements with toHaveLength(), avoiding direct fixture.debugElement queries for these cases.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.