[英]Angular tests failing after using APP_INITIALIZER to load config file
[英]Angular APP_INITIALIZER to load config file in tests
我正在使用此要點在應用程序啟動期間讀取配置文件。 這工作正常,但在進行單元測試時,我收到錯誤Cannot read property 'SomeProperty' of null
。
我也添加了提供程序進行測試
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
imports: [ReactiveFormsModule, RouterTestingModule, HttpModule],
providers: [AuthService,
SettingsService,
AppConfig,
{
provide: APP_INITIALIZER,
useFactory: initConfig,
deps: [AppConfig],
multi: true
},
]
})
.compileComponents();
}));
任何解決此問題的指針? 提前致謝。
看起來 Angular 在運行測試時如何處理 APP_INITIALIZER 存在問題(請參閱https://github.com/angular/angular/issues/24218 )。
現在的解決方法是在每個之前調用它:test
beforeEach(async () => {
// until https://github.com/angular/angular/issues/24218 is fixed
await TestBed.inject(ApplicationInitStatus).donePromise;
});
對於角度 <9,請改用 TestBed.get(...)。
我在這樣的事情上轉動了一段時間。 最后,我只是在 APP_INITIALIZER 提供程序的“deps”中提供了該服務的模擬,並確保它在單元測試中沒有做任何事情。
然后您只需獨立測試初始化程序和服務,我認為這是您能做的最好的事情。
我認為分開測試是個好主意。 所以,我將配置模擬到我的測試中並開始工作。 當然,我必須為 ConfigService 創建另一個規范。
describe('My unit test', () => {
const mock= { get myConfig() { return { url: 'http://mock' }; } };
...
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [...],
declarations: [...],
providers: [
{ provide: ConfigService, useValue: mock}
]
}).compileComponents();
...
});
...
});
參考: https : //gitmemory.com/issue/thymikee/jest-preset-angular/310/532370527
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.