Mocking Services and MatDialog Angular Unit Tests
November 10, 2021 · 5 min readLucian CiobanuI've spent the last three days writting unit tests and also learning a lot about them. One of the most challenges parts for me was mocking services which are imported and used in a component in order to test said components. The services I'm importing either return a value or an observable so I want to put down here how I've tested these components by mocking them.
I will mock a service using HTTP client, a Snacbar Service and a component which caches data for this component.
//imports in the tested component file
import { HomeCachingService } from '../shared/services/home-caching.service';
import { HomeService } from '../shared/services/home.service';
import { SnackbarService } from '../shared/snackbar/snackbar.service';
import { MatDialog } from '@angular/material/dialog';
const mockBody: MockBody = {
prop1: "prop value",
prop2: 200
}
// here I'd add the mock variables I'd like to pass as responses
// from the services
class HomeCachingServiceMock {
getHomeData() { };
//we will not add anything to be returned
}
//mocking http client service
class HomeServiceMock {
getValues() {
return of(undefined);
}
//add all the methods here and include "of"
//if an observable would be returned
//I add undefined at this point if there are some else
//conditions I need to go through on the success return
}
class SnackbarServiceMock {
showMessage() { };
//the snackbar service doesn't return anything,
//it just uses a method
}
class MatDialogMock() {
open() {
return {
afterClosed: () => of(true)
}
}
}
describe('HomeComponent', () => {
//create variables for each service which needs to be used
let homeCachingService: HomeCachingService;
let homeService: HomeService;
let snackbarService: SnackbarService;
let dialog: MatDialog;
beforeEach(async () => {
await TestBed.configureTestModule({
declarations: [ HomeComponent],
imports: [ /*add here your imported modules like HttpClientModule*/ ],
providers: [
//add here your mock classes to be used instead of the real services
{ provide: HomeService, useClass: HomeServiceMock },
{ provide: HomeCachingService, useClass: HomeCachingServiceMock },
{ provide: SnackbarService, useClass: SnackbarServiceMock },
{ provide: MattDialog, useClass: MatDialogMock }
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
//I always add this when using Material
})
.compileComponent();
});
beforeEach(() => {
[...]
//attribute to your variables the injected mocks
homeService = TestBed.inject(HomeService);
homeCachingService = TestBed.inject(HomeCachingService);
snackbarService = TestBed.inject(SanckbarService);
dialog = TestBed.inject(MatDialog);
});
//getting data from a caching service
it('should get data from caching service', () => {
const getData = spyOn(homeCachingService, 'getHomeData');
component.onTrigger();
expect(getData).toHaveBeenCalled();
//we will now test the call to getData from HomeService which returns
//200 or error
it('should get values', fakeAsync(() => {
spyOn(homeService, 'getValues').and.returnValue(of({status: 200}));
spyOn(component, 'nextMethodToBeTriggeredAfterCallWith200');
component.onMethodTriggeringCall();
tick(100); //wait 100 ms
expect(component.nextMethodToBeTriggeredAfterCallWith200).toHaveBeenCalled();
}));
//if you want to return an HTTP Response, you can do
it('should get values', fakeAsync(() => {
spyOn(homeService, 'getValues').and.returnValue(of(new HttpResponse({status: 200, body: [mockBody]}));
spyOn(component, 'nextMethodToBeTriggeredAfterCallWith200');
component.onMethodTriggeringCall();
tick(100); //wait 100 ms
expect(component.nextMethodToBeTriggeredAfterCallWith200).toHaveBeenCalled();
}));
it('should show error message', fakeAsync(() => {
spyOn(homeService, 'getValues').and.returnValue(throwError({errorText: 'text'}));
spyOn(snackbarServie, 'showMessage');
cmponent.onMethodTriggeringCall();
tick(100);
expect(snackbarService.showMessage).toHaveBeenCalled();
}));
it('should close dialog on submit', () => {
spyOn(dialogRef, 'close');
component.onSumbit();
expect(dialogRef.cloes).toHaveBeenCalled();
});
});
I will never suffer from Unit Tests again.. I hope!
Hope this helped!
Cheers,
Lucian

Web Development & Software Delivery