Answer the question
In order to leave comments, you need to log in
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;
}
}
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);
});
});
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);
});
});
CounterService > should be created
NullInjectorError: R3InjectorError(DynamicTestModule)[CounterService -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question