At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

Learn How: Unit testing Angular Component With Spectator

  • By Preethima K
  • November 14, 2019
  • 3087 Views

Working on unit testing can be a crucial part of any Angular project. If you are on the Test-Driven Development approach, there are a lot of benefits to it. In this blog, I will explain, how to unit test Angular component with Spectator.
By the way, let me brief, What is Spectator?
The spectator is a great tool to simplify the unit testing in Angular. It is used to write test cases for components, directives, and services. It is a boilerplate that provides the custom matches to test the HTML DOM element more easily. In this blog, we are using the Karma framework in Spectator for unit testing. 
In Angular, generally we need to mock up the functions for unit testing, One of the biggest advantages in Spectator is that we can call it directly in lesser time duration. 
Here are some of the important features of Spectator you should know,

  • Efficient DOM querying
  • It will support for jasmine and jest
  • HTTP and routing testing support
  • It will support testing for angular components, directives, and services
  • Supports for entry components and component providers

Let’s get started with the installation.

Installation

To install the Spectator, we can use any of the following ways to install the tool in your machine. One way is npm and the other is using Yarn. Install the tool in your convenient way. 

NPM

npm install @ngneat/spectator --save-dev

Yarn

yarn add @ngneat/spectator --dev

Testing Components

Events API

Events which are accepted as the spectator element can be used with any of the following,

type SpectatorElement = string | Element | DebugElement | ElementRef | Window | Document;

If the Spectator element is not provided, the default will be the host element of the component.
click() will trigger the mouse click event.

spectator.click(SpectatorElement);

blur() will trigger the blur event when focussing out of an element.

spectator.blur(SpectatorElement);

focus() will trigger the focus event when the field is active.

spectator.focus(SpectatorElement);

typeInElement() will Simulate the user typing.

spectator.typeInElement(value, SpectatorElement);

dispatchTouchEvent() will Trigger the touch event.

spectator.dispatchTouchEvent(SpectatorElement, type, x, y);

Queries

In some cases, we may need to handle a query which is the global level, other than component level. With Spectator, we can do global querying using the root key by the following method.

const element = spectator.query('.some-overlay', {
 root: true
})

Global Injections

Spectator provides the option to use global configuration, in some cases, we may need to use the same configuration across multiple components, modules or providers. In those scenarios, this will be highly helpful. We can use define GlobalsInjections() helper in the test setup.

Mock Providers

We can use the mock option to auto mock the providers. Depending on the class definition it will create the mock object automatically using Jasmine or Jest.  For instance, if you want to mock a component, providers, directives,  we can use ng-mocks in these cases. 
There is no need to import any component, providers, directives, to directly give to mocks option. In case if there is a necessity to replace any child component we can make use of the dummy process. 

import { MockComponent, MockDirective } from 'ng-mocks';  
           const createComponent = createComponentFactory({
  Component: appComponent
  mocks: [FooService],                // will create a mocked provider
  declarations: [
    MockComponent(FooComponent), // will create a mocked child component
    MockDirective(BarDirective), // directive
  ]
});

Spectator Services

It is pretty simple to implement a Spectator for service testing and to create factory service – createServiceFactory Which returns the factory
It can access the created service using the spectator.service 

import { SpectatorService, createServiceFactory } from '@ngneat/spectator';
describe(appService, () => {
  let spectator: SpectatorService<SomeService>;
  const createService = createServiceFactory(appService);
  beforeEach(() => spectator = createService());
  it('should appService, () => {
    spectator.service.serviceMethod();
  });
}

Spectator for HTTP

The spectator can perform an HTTP request and creates a factory data service: createHttpFactory it will return a factory SpectatorHttp. These are the following members,
service – Returns the created service
expectOne(URL: string, method: HttpMethod) – To assert a request and return the TestRequest
httpClient – To access the HttpClient from Angular
controller – To access the HttpTestingController from Angular

import { SpectatorHttp, createHttpFactory, HttpMethod } from '@ngneat/spectator';  
import { appDataService } from './app-data.service';  
describe('HttpClient testing', () => {  
  let spectator: SpectatorHttp<appDataService>;
  const createHttp = createHttpFactory(appDataService);  
  beforeEach(() => spectator = createHttp()); 
  it('should retrieve data from API', () => {
    spectator.service.getDatas().subscribe();
    spectator.expectOne('api/data, HttpMethod.GET);
  });  
});

Conclusion

These bunch of features will help you test angular components. The spectator is one of the amazing tools I’ve tried for angular testing. The steps are quite simple and easy to understand, perform different kinds of testing components. I hope this will help in testing your Angular application.
And also tell me, what tool do you use for testing the angular components?
If you have any doubts or suggestions on this post, let us know in the comment section below. Visit our blog for more recent posts on Angular development. Subscribe now for all exclusive weekly!
Don’t let your ideas fade away over time! Get started with your Angular projects right away with Agira. Hire highly skilled developers in the industry.

Turn your vision to magnificent reality With
Our Web and Mobile Solutions