Error: Unexpected value 'CookieService' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation

1.9k Views Asked by At

I'm trying to test a service with jasmine but i have this error:

Error: Unexpected value 'CookieService' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.

and

Error: Expected undefined to be truthy.

My spec file:

import { RouterTestingModule } from '@angular/router/testing';
import { TestBed } from '@angular/core/testing';
import { Api } from './api.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, Inject, Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie';

fdescribe('ApiService', () => {
  let service: Api;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        Api,

      ],
      imports: [
        HttpClientTestingModule,
        RouterTestingModule,
        CookieService
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
    });
  });

  beforeEach(() => {
    service = TestBed.inject(Api);
    httpMock = TestBed.inject(HttpTestingController);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

});
1

There are 1 best solutions below

2
Yong Shun On BEST ANSWER

This error message shows as CookieServie is not a NgModule.

Error: Unexpected value 'CookieService' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.

As Ngx-Cookie documentation,

Add the cookie service to your app.module.ts as a provider:


Solution

You have to remove CookieService from imports section and add it into providers section.

.spec.ts

TestBed.configureTestingModule({
  providers: [
    Api,
    CookieService
 ],
 imports: [
   HttpClientTestingModule,
   RouterTestingModule
 ],
 schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
});

Sample solution on StackBlitz