Home > OS >  ANGULAR CRUD httpclient error in my service.spec.ts
ANGULAR CRUD httpclient error in my service.spec.ts

Time:08-03

I was trying to create the user service and importing httpclient, when i did that i recieved an error in my service.spec.ts on 'new UserService' saying 'An argument for 'httpClient' was not provided' what should i do????

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { UserComponent } from './user/user.component';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
  declarations: [
    AppComponent,
    UserComponent
  ],
  imports: [
    FormsModule,
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    NgbModule,
  ],
  providers: [HttpClientModule,],
  bootstrap: [AppComponent]
})
export class AppModule { }

import { Injectable } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({providedIn :'root'})
export class UserService {
    readonly API_URL ='http://localhost:8080/api/user';

    constructor(private httpClient : HttpClient){}
    addUser(user : any){
        return this.httpClient.post('${this.API_URL}/adduser', user)
    }
    updateUser(user: any){
        return this.httpClient.put('${this.API_URL}/updateuser', user)
    }
    deleteUser(idUser: any){
        return this.httpClient.delete('${this.API_URL}/deleteuser/${idUser}')
    }
    getAllUsers(){
        return this.httpClient.get('${this.API_URL}/allusers')
    }
}
import { UserService } from './user-service';
import { HttpClient, HttpHandler } from '@angular/common/http';
describe('UserService', () => {
  it('should create an instance', () => {
    expect(new UserService()).toBeTruthy();
  });
});

CodePudding user response:

Declare a type of HttpClient as it is a dependency in your service. This will look something like below code in your spec.ts file.

describe('UserService', () => {
  let httpClient: HttpClient;
  it('should create an instance', () => {
    expect(new UserService(httpClient)).toBeTruthy();
  });

CodePudding user response:

as you are testing service and the constructor has httpClient, you need to configure the HttpClient/HttpClientTestingModule in beforeEach

import { HttpHandler } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { UserService } from './user-service';

describe('UserService', () => {
   let userService : UserService;

 beforeEach(async () => {
  await TestBed.configureTestingModule({
  imports: [HttpClientTestingModule],
  service=TestBed.inject(userService); })
 })

   it('should create an instance', () => {
   expect(service()).toBeTruthy();
  });
 })
  • Related