Home > Back-end >  ng test problem while testing a component
ng test problem while testing a component

Time:09-24

I have the following error when I ng test component on Angular 12:

Error: Unexpected value 'ParamDecoratorFactory' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation. at verifySemanticsOfNgModuleDef (http://localhost:9876/karma_webpack/vendor.js:85197:19) at http://localhost:9876/karma_webpack/vendor.js:85208:9 at Array.forEach () at verifySemanticsOfNgModuleDef (http://localhost:9876/karma_webpack/vendor.js:85206:60) at Function.get (http://localhost:9876/karma_webpack/vendor.js:85168:21) at R3TestBedCompiler.applyProviderOverridesToModule (http://localhost:9876/karma_webpack/vendor.js:92502:39) at R3TestBedCompiler.compileTestModule (http://localhost:9876/karma_webpack/vendor.js:92750:14) at R3TestBedCompiler.finalize (http://localhost:9876/karma_webpack/vendor.js:92356:14) at TestBedRender3.get testModuleRef [as testModuleRef] (http://localhost:9876/karma_webpack/vendor.js:93229:49) at TestBedRender3.inject (http://localhost:9876/karma_webpack/vendor.js:93152:29)

Error: Expected undefined to be truthy. at at UserContext. (http://localhost:9876/karma_webpack/main.js:1060:23) at ZoneDelegate.invoke (http://localhost:9876/karma_webpack/polyfills.js:382:26) at ProxyZoneSpec.onInvoke (http://localhost:9876/karma_webpack/vendor.js:120678:39)

The spec.ts code is this:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Inject } from '@angular/core';
import { MenuComponent } from './menu.component';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';
import { flyInOut, expand } from '../animations/app.animation';

describe('MenuComponent', () => {
  let component: MenuComponent;
  let fixture: ComponentFixture<MenuComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        Inject,
        Dish,
        DishService,
        flyInOut,
        expand
      ],
      declarations: [ MenuComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MenuComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});

The component.ts code is this:

import { Component, OnInit, Inject } from '@angular/core';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';
import { flyInOut, expand } from '../animations/app.animation';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.scss'],
  // tslint:disable-next-line:use-host-property-decorator
  host: {
    '[@flyInOut]': 'true',
    'style': 'display: block;'
    },
  animations: [
    flyInOut(),
    expand()
  ]
})
export class MenuComponent implements OnInit {

  dishes!: Dish[];
  errMess: string;
  
  constructor(private dishService: DishService, 
    @Inject ('BaseURL') public baseURL) { }

  ngOnInit(): void {
    this.dishService.getDishes().subscribe((dishes => this.dishes = dishes), errMess => this.errMess = <any>errMess);
  }

}

This is the dish.service.ts code:

import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { baseURL } from '../shared/baseurl';
import { map, catchError } from 'rxjs/operators';
import { ProcessHTTPMsgService } from './process-httpmsg.service';

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

  constructor(private http: HttpClient, private processHTTPMsgService: ProcessHTTPMsgService) { }

  getDishes(): Observable<Dish[]> {
    return this.http.get<Dish[]>(baseURL   '/dishes').pipe(catchError(this.processHTTPMsgService.handleError));
  }

  getDish(id: string): Observable<Dish> {
    return this.http.get<Dish>(baseURL   '/dishes/'   id).pipe(catchError(this.processHTTPMsgService.handleError));
  }

  getFeaturedDish(): Observable<Dish> {
    return this.http.get<Dish[]>(baseURL   '/dishes?featured=true').pipe(map(dishes => dishes[0])).pipe(catchError(this.processHTTPMsgService.handleError));
  }

  getDishIds(): Observable<string[] | any> {
    return this.getDishes().pipe(map(dishes => dishes.map(dish => dish.id))).pipe(catchError(error => error));
  }

  putDish(dish: Dish): Observable<Dish> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json'})
    };
    return this.http.put<Dish>(baseURL   '/dishes/'   dish.id, dish, httpOptions).pipe(catchError(this.processHTTPMsgService.handleError));
  }
}

Appreciate your help

CodePudding user response:

imports array expects only Module(eg: FormsModule, translation module etc). Here you are adding services into the imports list.

Instead please add it inside providers list in your spec.ts file.

describe('MenuComponent', () => {
  let component: MenuComponent;
  let fixture: ComponentFixture<MenuComponent>;

  // mocking service to avoid actual HTTP calls
  const mockDishService = {
     getDishes: () => {
        // sample JSON similar to api response
        return {
           id: '000',
           name: 'nnnnn'
        }
     }
  }

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [], // no module dependency so keeping it []
      declarations: [ MenuComponent ],
      providers: [
        { provide: DishService, useValue: mockDishService }
      ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MenuComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});
  • Related