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

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

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'; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!