Angular Unit Testing with Jasmine: Code Snippets

Jeni Joe
2 min readJan 3, 2021

1.Testing a DialogService that opens a Material Dialog pop-up component CommonDialogComponent with mocks and spyOn

import { DialogService } from './dialog.service';
import { CommonDialogComponent } from './src/app/components/common-dialog/common-dialog.component';
import { By } from '@angular/platform-browser';
describe('DialogService', () => {
let component: CommonDialogComponent;
let fixture: ComponentFixture<CommonDialogComponent>;
const dialogMock = {
close: () => {}
};
let service: DialogService; beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatDialogModule, BrowserAnimationsModule],
declarations: [CommonDialogComponent],
providers: [
{ provide: MatDialogRef, useValue: dialogMock },
{ provide: MAT_DIALOG_DATA, useValue: [] }
]
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should show dialog', () => {
let dialogServ = TestBed.get(MatDialog);
let spy = spyOn(dialogServ, 'open');
service.showDialog({});
expect(spy).toHaveBeenCalled();
});
});

2. Testing Angular Router for navigation to another page with history

class RouterStub {
navigate(params) {}
}
//in the beforeEach providers array:
TestedService,
{ provide: Router, useClass: RouterStub }
//unit test
it('should redirect to page2 when goToPageTwo button is clicked',
() => {
let router = TestBed.get(Router);
let spy = spyOn(router, 'navigate');
window.history.pushState({ state: {
"stateObjName": "objValue"
}, '', '');
component.goToPageTwo();
expect(spy).toHaveBeenCalledWith(['pageTwo']);
});

3. Mocking injected Services in components. ServiceOne and ServiceTwo are injected into the component using dependency injection in the constructor.
myJson is the JSON response from the services.

import { of } from 'rxjs/internal/observable/of';describe('UserComponent', () => {
let component: UserComponent;
let fixture: ComponentFixture<UserComponent>;
beforeEach(() => {
const MockServiceOne = jasmine.createSpyObj('ServiceOne', ['getById']});
MockServiceOne.getById.and.returnValue(of({obj: myJson.content[0]
}));
TestBed.configureTestingModule({
...
providers: [
ServiceTwo,
{ provide: ServiceOne, useValue: MockServiceOne }
...
]
...
it('should create', () => {
let service = TestBed.get(ServiceTwo);
spyOn(service, 'getAll').and.returnValue(of(
{ objList: myJson,
"sortOrder": "desc"
}));
// Angular initiates data binding and calls lifecycle hooks
fixture.detectChanges();
expect(component).toBeTruthy();
}

4. Mocking back navigation with Location object

import { Location } from '@angular/common';...
providers: [
...
Location
]
...
it('should call location.back when back button is clicked', () => {
let loc = TestBed.get(Location);
let locSpy = spyOn(loc, 'back');
component.backClick();
expect(locSpy).toHaveBeenCalled();
}

5. Testing a component with an Angular FormBuilder form that is used for filling in details and on submission, issues a POST HTTP request through an injected service.
The form uses the following Angular Material components: Select, Input, Slider

import { FormBuilder, FormsModule, ReactiveFormsModule, FormControl, Validators } from '@angular/fomrs';
import { HttpClientModule } from '@angular/common/http';
import { MatFormFieldModule, MatLabel } from '@angular/material/form-field';
import { MatSliderModule } from '@angular/material/slider';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
class CRUDServiceStub {
create() {
return;
}
}
...beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
MatSelectModule,
MatSliderModule,
MatInputModule,
FormsModule,
ReactiveFormsModule
],
declarations: [ CreateObjectWithFormComponent ],
providers: [
FormBuilder,
{ provide: CRUDService, useValue: CRUDServiceStub },
...
]
...it('should call CRUDService's create method when create button is clicked', () => {
let service = TestBed.get(CRUDService);
let createServiceSpy = spyOn(service, 'create').and.returnValue(of({
"code": "",
"message": ""
}));
//get a handle on the FormBuilder
let formBuilder = TestBed.get(FormBuilder);
//mocking form
component.form = formBuilder.group({
emailFormControl: new FormControl(
"abc@def.com",
Validators.email
),
nameFormControl: new FormControl(
"Name1",
Validators.required
)
});
component.onSubmit();
expect(createServiceSpy).toHaveBeenCalled();
});

--

--