0

I'm trying my hand at creating an Angular unit test, but failing right off the bat.

I've taken a look at this and this this SO, which seems to be exactly what I'm struggling with, but after attempting the fixes mentioned there, I am still not coming right.

This is my code :

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

import { ContactsService } from './contacts.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';

describe('ContactsService', () => {


   beforeEach(() => {
     TestBed.configureTestingModule({
       imports: [ HttpClientTestingModule, ContactsService, HttpClient],
  })
  .compileComponents();
  });


});

When I run an ng test, I get this error :

NullInjectorError: R3InjectorError(DynamicTestModule)[ContactsService -> HttpClient -> HttpClient]: NullInjectorError: No provider for HttpClient!

My .ts, for completeness :

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Entry } from '../classes/entry';
import { EntrySearch } from '../classes/entrySearch';

@Injectable({
  providedIn: 'root'
})
export class ContactsService {

  constructor(private http: HttpClient) { }

}
WynDiesel
  • 1,104
  • 7
  • 38
  • This answer on the duplicate target answers perfectly:https://stackoverflow.com/a/47261579/5468463 – Vega Feb 23 '21 at 17:27

2 Answers2

0

You just need to import HttpClientTestingModule and provide your ContactsService:

import { ContactsService } from './contacts.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';

describe('ContactsService', () => {
  beforeEach(() => TestBed.configureTestingModule({
    imports: [ HttpClientTestingModule ],
    providers: [ ContactsService ]
  }));

 it('should be created', () => {
    const service: ContactsService = TestBed.inject(ContactsService);
    expect(service).toBeTruthy();
   });
});
tilo
  • 14,009
  • 6
  • 68
  • 85
0

Yeah, it is like tilo says, it should have worked. And also try to make your beforeEach - async().

Try this - a little bit modified (see the declarations part):

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

import { ContactsService } from './contacts.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';

describe('ContactsService', () => {


   beforeEach(async(() => {
     TestBed.configureTestingModule({
       declarations: [ContactsService],
       imports: [ HttpClientTestingModule]
  })
  .compileComponents();
  }));


});
st_stefanov
  • 1,147
  • 1
  • 10
  • 28