![](/img/trans.png)
[英]Angular 2 No Provider or DI error (Uncaught (in promise): Error: No provider …)
[英]Error in Angular Test using Karma: Uncaught (in promise): Error: No provider for SessionUtil
我正在嘗試為Angular應用程序編寫一些測試。 我正在用Jasmin / Karma / PhantomJS編寫測試,但是不斷出現錯誤,這使我的所有測試均失敗,這是Error: No provider for SessionUtil!
SessionUtil是一種實用程序類/服務,具有許多公共方法。 在我的main.component.ts文件中,我像這樣將其注入到我的構造器中
constructor(@Inject(SessionUtil) private sessionUtil: SessionUtil)
這是我的測試文件(不是全部,只是我聲明所有內容並導入服務的地方,等等)
describe('MainComponent', () => {
let componentFixture: ComponentFixture<MainComponent>;
let instance: any;
let element: any;
let sessionUtil: SessionUtil;
let spyLocalizationsService;
const firstLanguage = 'en-US';
const secondLanguage = 'de-DE';
const unknownLanguage = 'xx-XX';
beforeEach(async(() => {
spyLocalizationsService = sinon.createStubInstance(LocalizationsService);
spyLocalizationsService.changeLanguage.withArgs(firstLanguage, sinon.match.any, sinon.match.any).callsArg(1);
spyLocalizationsService.changeLanguage.withArgs(secondLanguage, sinon.match.any, sinon.match.any).callsArg(1);
spyLocalizationsService.changeLanguage.withArgs(unknownLanguage, sinon.match.any, sinon.match.any).callsArg(2);
spyLocalizationsService.getSupportedLanguages.returns([firstLanguage, secondLanguage]);
(sinon.stub(spyLocalizationsService, 'currentLanguage') as any).get(() => firstLanguage);
// Allows overriding default providers, directives, pipes
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([
// some Paths
]),
TranslateI18NextTestingModule.forRoot(),
AuthTestingModule.forRoot(),
NoopAnimationsModule,
MaterialModule
],
declarations: [
MainComponent,
DummyComponent
],
schemas:
[CUSTOM_ELEMENTS_SCHEMA],
providers:
[{provide: LocalizationsService, useValue: spyLocalizationsService},
{provide: MATERIAL_COMPATIBILITY_MODE, useValue: true}]
}).compileComponents().then(() => {
componentFixture = TestBed.createComponent(MainComponent);
element = componentFixture.nativeElement;
instance = componentFixture.componentInstance; // BannerComponent test instance
sessionUtil = componentFixture.debugElement.injector.get(SessionUtil);
});
}));
const isAuthenticated = () => Promise.resolve({
isAuthenticated: true,
username: 'Max Musterman'
});
describe('on init', () => {
beforeEach(async(() => {
sinon.stub(sessionUtil, 'isAuthenticated').returns(isAuthenticated());
}));
當我運行測試時,我僅收到以下錯誤,並且Uncaught (in promise): Error: No provider for SessionUtil!
運行任何測試, Uncaught (in promise): Error: No provider for SessionUtil!
我顯然做錯了。 我試圖將SessionUtil
注入TestBed.configureTestingModule
對象providers
數組中,但這給了我很多問題。 誰能看到我是如何錯誤地注射這種葯物的?
任何意見,將不勝感激!
{provide: SessionUtil, useValue: sessionUtil}
而且您需要使用存根啟動sessionUtil
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.