gpt4 book ai didi

javascript - Angular 4 单元测试,但出现错误 No provider for Http

转载 作者:行者123 更新时间:2023-11-30 20:45:54 26 4
gpt4 key购买 nike

我正在尝试学习如何在 angular 4 上运行单元测试组件,但我没有成功,当我使用下面的代码运行测试时出现此错误:

Error: No provider for http! and Failed: : could not find an object to spy upon for filexGeneralData()

不知道我走的对不对...

看看我的代码

我的规范文件

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpModule } from '@angular/http';

import { of } from 'rxjs/observable/of';
import { filex } from '../../../models/filex';
import { filexService } from '../../../services/filex.service';
import { fileyfilexComponent } from './filey-filex.component';
import { dataService } from '../../../services/data.service';

describe('fileyfilexComponent', () => {
let filexService;
let myComponent;
let fixture;
let element;

beforeEach(
async(() => {
TestBed.configureTestingModule({
declarations: [fileyfilexComponent],
providers: [filexService, dataService],
imports: [HttpModule]
}).compileComponents();
})
);

beforeEach(inject([filexService], s => {
filexService = s;
fixture = TestBed.createComponent(fileyfilexComponent);
myComponent = fixture.componentInstance;
element = fixture.nativeElement;
}));

it(
'should call getUsers and return list of users',
async(() => {
const response: filex[] = [];

spyOn(filexService, 'filexGeneralData').and.returnValue(of(response));

myComponent.method1();

fixture.detectChanges();

expect(myComponent.datafilex).toEqual(response);
})
);
});

最佳答案

您只需将 HubWrapperComponent 包含在您的 TestBed 中。在 providers 数组中,您需要包含提供给被测组件的所有服务(更好的是,您应该提供这些服务的“模拟”版本)。因此,您可以通过简单地将 HubWrapperComponent 添加到 spec 文件的 TestBed 中的 providers 数组来使错误“消失”。 configureTestingModule 方法。它最终看起来像这样:

规范:

TestBed.configureTestingModule({
declarations: [IndicatorsDashboardComponent],
providers: [DashboardService, DadosService, HubWrapperComponent],
imports: [HttpModule]
}).compileComponents();

另外一条建议:我建议使用 jasmine 来模拟你的 HubWrapperComponent(它似乎是 HttpClient 的包装器?)。

mockWrapper = jasmine.createSpyObj('http', ['get']);

然后在您的 providers 数组中:

{provide: HubWrapperComponent, useValue: mockWrapper}

这种方法看起来像这样:

  let mockHub: SpyObj<HubWrapperComponent>;

beforeEach(
async(() => {
mockHub = jasmine.createSpyObj('http', ['get']);

TestBed.configureTestingModule({
declarations: [IndicatorsDashboardComponent],
providers: [
DashboardService,
DadosService,
{ provide: HubWrapperComponent, useValue: mockHub }
],
imports: [HttpModule]
}).compileComponents();
})
);

模拟服务/任何进行 Http 调用的东西是首选,因为您不想在测试中发出真正的请求。

关于javascript - Angular 4 单元测试,但出现错误 No provider for Http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48710238/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com