0

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();
  });

});
Pavan Jadda
  • 4,306
  • 9
  • 47
  • 79

1 Answers1

0

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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • great, but i have a new problem XD, this is: NullInjectorError: R3InjectorError(DynamicTestModule)[Api -> CookieService -> CookieOptionsProvider -> CookieOptionsProvider]: NullInjectorError: No provider for CookieOptionsProvider! –  Aug 02 '21 at 02:49
  • You need to add `CookieModule.forRoot()` into `imports` section. You may refer to this [GitHub issue](https://github.com/salemdar/ngx-cookie/issues/10). – Yong Shun Aug 02 '21 at 02:53