Z
Z
zlodiak2021-04-16 20:14:36
Angular
zlodiak, 2021-04-16 20:14:36

How to take into account the presence of httpClient in a unit test?

I wrote a unit test for such a service:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class CounterService {
  count: number = 0;

  constructor() {}

  getCounter() {
    return this.count;
  }
}


Here is the unit test:

import { TestBed } from '@angular/core/testing';
import { CounterService } from './counter.service';

describe('CounterService', () => {
  let service: CounterService;

  beforeEach(() => {
    TestBed.configureTestingModule({ });
    service = TestBed.inject(CounterService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should be equal 0 after init', () => {
    expect(service.getCounter()).toBe(0);
  });
});


With this test, everything is OK, it fulfills successfully.

But the error appears when I try to add httpClient to the service:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class CounterService {
  count: number = 0;

  constructor(private http: HttpClient) {}

  getCounter() {
    return this.count;
  }
}


import { TestBed } from '@angular/core/testing';

import { CounterService } from './counter.service';

describe('CounterService', () => {
  let service: CounterService;

  beforeEach(() => {
    TestBed.configureTestingModule({ providers: [CounterService] });
    service = TestBed.inject(CounterService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should be equal 0 after init', () => {
    expect(service.getCounter()).toBe(0);
  });
});


In this scenario, the tests do not complete successfully, and the following error is displayed:
CounterService > should be created 
NullInjectorError: R3InjectorError(DynamicTestModule)[CounterService -> HttpClient -> HttpClient]: 
NullInjectorError: No provider for HttpClient!


Please help me fix the unit test

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tigran Abrahamyan, 2021-04-16
@zlodiak

https://stackoverflow.com/questions/53769401/angul...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question