问题
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.
Any one 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();
});
});
回答1:
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);
});
回答2:
You have to import HttpClientModule in your module file
import {HttpClientModule} from '@angular/common/http';
来源:https://stackoverflow.com/questions/52116993/jasmin-karma-error-unexpected-value-httpclient-imported-by-the-module-dy