vendredi 19 juin 2020

How to solve “Invalid provider for the NgModule 'DynamicTestModule” in Angular 9?

I am working in angular project and i try to run test cases for signin component and I am getting this error from auth.service.ts when I run test cases it shows Invalid provider for the NgModule 'DynamicTestModule' - only instances of Provider and Type are allowed, got: [..., ..., ..., ?undefined?, ...] error

Here is my signin.component.spec.ts:

import { NO_ERRORS_SCHEMA,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {AuthService} from '../../../services/auth/auth.service';
import { SigninComponent } from './signin.component';
import { ConfirmationService } from 'primeng/api';
import { RouterTestingModule } from '@angular/router/testing';
import {HttpClientTestingModule} from '@angular/common/http/testing';
import { NGXLogger } from 'ngx-logger';

describe('SigninComponent', () => {
  let component: SigninComponent;
  let AuthService:AuthService;
  let fixture: ComponentFixture<SigninComponent>; 
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers:[
        ConfirmationService, AuthService,
        { provide: NGXLogger, useClass: class {} }
          ],
      declarations: [ SigninComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA,NO_ERRORS_SCHEMA],
      imports:[HttpClientTestingModule,RouterTestingModule.withRoutes([]),]
    })
    .compileComponents();
    fixture = TestBed.createComponent(SigninComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    AuthService = fixture.debugElement.injector.get(AuthService);
  }));


  it('check for signin', () => {
   AuthService.login({ 'email': "abc@gmail.com", 'password': "abc" }, true).subscribe(
      (res: boolean) => {
        if(res){
          console.log("login res",res);
          expect(res).toBeTrue();
        }
      });
  });
});

and my auth.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpEvent, HttpResponse } from '@angular/common/http';
import { environment } from '../../../environments/environment';
import { Observable,BehaviorSubject } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { NGXLogger } from 'ngx-logger';

and here is login implementation:

 public login(usercreds: any, record: boolean): Observable<boolean> {
        let url: string = environment.apiEndpoint + '/token';
        let body: any = { 'email': usercreds.email, 'password': usercreds.password };
        let headers: HttpHeaders = new HttpHeaders().set('Content-Type', 'application/json');

        return this.http.post<ITokenMsg>(url, body, { headers: headers })
            .pipe(
                map((value: ITokenMsg): boolean => { return this.handleAuthResponse(value.token, record); }),
                catchError((err: any) => { return this.handleAuthError(err); }),
        );
    }

1 commentaire: