Angular Unit Test: Mock Service and Observables — Part 1

Piyush Jain
7 min readSep 9, 2022
Source -https://liftoff.io/blog/ad-creative-testing-tips/

What is unit testing

A unit test is testing the smallest piece of code that can be logically isolated in the system.
Unit testing helps us to improve quality of code. It also helps to make easier for developers to add new features by modifying existing code.

In this article we will learn how to write unit test when you hit HTTP calls.

In this article we are not going to learn how to setup jest in angular. So for this we will clone Github repo.

Github Repo: https://github.com/piyush303/angular-jest

We will be using dummy API which are available online.
https://jsonplaceholder.typicode.com/users

Lets start

First of all we will add some npm dependencies which will be required when we will write unit tests for mocking service and for testing DOM.

npm install --save-dev @testing-library/angular @testing-library/dom jest-auto-spies @testing-library/user-event@13

Now we need to add HttpClientModule in app.module.ts under imports array.
Once you will import this our app.module.ts will look like below.

import { NgModule } from…

--

--

Piyush Jain

An avid front-end technologist with 9+ years of web industry experience. Self-motivated professional with broad technical skill-set and very strong attention.