Jasmin + karma:“错误:模块'DynamicTestModule'导入的意外值'HttpClient'。请添加一个@NgModule注释。“

问题描述 投票:3回答:2

我使用茉莉作为测试框架,并将业力作为测试运行者。我正在尝试创建一个HttpClient对象,以便我可以创建一个服务,作为该对象的依赖:

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

但是我收到以下错误:

错误:模块'DynamicTestModule'导入的意外值'HttpClient'。请添加@NgModule注释。

任何人都知道如何解决这个问题?

遵循所有代码:

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();
    });
});
angular typescript unit-testing jasmine
2个回答
6
投票

当您尝试在declarations数组中包含除组件,指令或管道之外的其他内容时,会引发编译错误。

我重构了你的测试规范,从声明模块中删除HttpClient,导入HttpClientTestingModule,因为它比HttpClientModuletesting有一些明显的优势,并使用稍微不同的模式创建你的I18nService实例传递给你的模型类。

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

    describe('TestSpec', () => {

    let intlService = I18nService;

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

    i18nService = TestBed.Get(I18nService);
});

0
投票

您必须在模块文件中导入HttpClientModule

import {HttpClientModule} from '@angular/common/http';
© www.soinside.com 2019 - 2024. All rights reserved.