Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmin + karma: "Error: Unexpected value 'HttpClient' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation."

I'm using jasmine as a test framework and karma as a test runner. I'm trying to create an HttpClient object so I could create a service that as a depedency to this object:

TestBed.configureTestingModule({
    declarations: [HttpClient],
    imports: [HttpClient],
    providers: [HttpClient]
});
TestBed.get(HttpClient);

But I'm getting the following error:

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

Does anyone have an idea how to solve this?

Follows all the code:

import { I18nService } from "../../services/i18n.service";
import { TestBed, inject, async } from "@angular/core/testing";
import { EditionHistoryEventsModel } from "./dropdown.edition.history.events.model";
import { HttpClient } from "@angular/common/http";
import { TestUtil } from "../../utils/test.uti";



describe('DropDownEditionHistoryItemModel', () => {
    let i18nService: I18nService;
     
    beforeAll(() => {
        TestBed.configureTestingModule({
            declarations: [HttpClient],
            imports: [HttpClient],
            providers: [HttpClient]
        });
        i18nService = TestUtil.geti18nService(TestBed.get(HttpClient));
    });
    it('asdasd', () => {
        let model: EditionHistoryEventsModel = new EditionHistoryEventsModel(i18nService);
        expect(true).toBeTruthy();
    });
});
like image 746
Ricardo Rocha Avatar asked Aug 31 '18 13:08

Ricardo Rocha


1 Answers

The compilation error you get is thrown when you try to include something other than a component, directive, or pipe in the declarations array.

I've refactored your test spec to remove the HttpClient from the declarations module, import the HttpClientTestingModule since it has some significant advantages over the HttpClientModule for testing, and used a slightly different pattern to create an instance of your I18nService to pass to your model class.

import { HttpClientTestingModule } from '@angular/common/http/testing';

    describe('TestSpec', () => {

    let intlService = I18nService;

    beforeAll(() => {
        TestBed.configureTestingModule({
            declarations: [],
            imports: [HttpClientTestingModule],
            providers: [I18nService]
    });

    i18nService = TestBed.Get(I18nService);
});
like image 134
ericksoen Avatar answered Nov 16 '22 04:11

ericksoen