[英]No provider for $injector in Angular Testing
我一直在嘗試在我們的Hybrid AngularJS / NG6應用程序中設置測試,但是這很難做到。 我不斷得到錯誤。 最新的是以下內容:
錯誤:StaticInjectorError(DynamicTestModule)[$ injector]:
StaticInjectorError(平台:核心)[$ injector]:
NullInjectorError:沒有$ injector的提供者!
我有以下component
:
import { Component, OnInit, Input, Inject } from '@angular/core';
import { DashboardService } from '../../services/dashboard/dashboard.service';
@Component({
templateUrl: './views/components/dashboard/dashboard.component.html'
})
export class DashboardComponent implements OnInit {
@Input()
Session;
Util;
constructor(
private _dashboardService: DashboardService,
@Inject('Session') Session: any,
@Inject('Util') Util: any
) {
this.Session = Session;
this.Util = Util;
}
ngOnInit() {
this._dashboardService
.getPrograms(this.Session.user.organization)
.subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
}
);
}
}
這完全沒問題。 我可以從我們的API中提取數據。 另一方面,我有這個spec
文件:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { DashboardComponent } from './dashboard.component';
import { DebugElement } from '@angular/core';
import { DashboardService } from '../../services/dashboard/dashboard.service';
import { ApiService } from '../../services/api.service';
import { HttpClientModule } from '@angular/common/http';
describe('The Dashboard', () => {
let component: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
let de: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule
],
declarations: [DashboardComponent],
providers: [
{
provide: 'Util',
useFactory: ($injector: any) => $injector.get('Util'),
deps: ['$injector']
},
{
provide: 'Session',
useFactory: ($injector: any) => $injector.get('Session'),
deps: ['$injector']
},
DashboardService,
ApiService
]
})
.overrideComponent(DashboardComponent, {
set: {
templateUrl:
'/dist/views/components/dashboard/dashboard.component.html'
}
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DashboardComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
當我運行此spec
文件時,我得到上面列出的錯誤。 我不知道這個錯誤試圖告訴我什么,因為它很模糊。
如何將$Injector
模塊正確提供到spec
文件中?
我還嘗試在我的混合應用程序中測試Angular部件與AngularJS的依賴關系,但我沒有成功。 要測試具有Angular依賴關系的AngularJS部件或具有AngularJS依賴關系的Angular部件是非常困難的。
我在GitHub上發現了這個帖子的兩個可能的解決方案
- 完全模擬其他框架中的部件。
- 創建包含來自其他框架的所有依賴項的迷你應用程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.