2017-10-10 59 views
1

我想爲我的Angular應用程序編寫一些測試。我寫我的茉莉/噶/ PhantomJS測試,我不斷收到這讓我所有的測試失敗,這是Error: No provider for SessionUtil!錯誤角度測試使用Karma:未捕獲(承諾):錯誤:沒有提供者SessionUtil

SessionUtil是一個實用工具類/服務,它擁有衆多的公共方法是錯誤的。在我main.component.ts文件我把它注射到我的construtor像這樣

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!我顯然做錯了什麼。我試圖在TestBed.configureTestingModule對象providers數組中注入SessionUtil,但這給了我很多問題。任何人都可以看到我如何注入這不正確?

任何意見將不勝感激!

回答

0
{provide: SessionUtil, useValue: sessionUtil} 

而且你需要啓動sessionUtil與存根

相關問題