![](/img/trans.png)
[英]Getting ReadableStream as body mocking http backend in angular2 unit test
[英]Angular 4 unit test, but getting error No provider for Http
我正在嘗試學習如何在 angular 4 上運行單元測試組件,但我沒有成功,當我使用下面的代碼運行測試時,出現此錯誤:
錯誤:http 沒有提供程序! 並且失敗了:: 找不到要監視的文件xGeneralData() 的對象
我不知道我是否走對了路...
看看我的代碼
我的規范文件
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.configureTestingModule
方法中的providers
數組來使錯誤“消失”。 它最終看起來像這樣:
規格:
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
調用的內容,因為您不想在測試中發出真正的請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.