我目前正在尝试为 ionic 编写测试。我的自动生成的测试在执行异步回调之前完成。如何检测构造函数中的回调何时完成以便我可以运行检查?
Promise 不是一个选项,因为 TestBed.createComponent 已经返回固定装置并且无法返回 Promise。
如果我要实现一个 did() 回调,我就必须修改构造函数签名以包含回调,这感觉是不好的做法。
测试文件:
it('should initialize the app', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
of(expect(platformSpy.ready).toHaveBeenCalled()).subscribe(async () => {
expect(statusBarSpy.styleDefault).toHaveBeenCalled();
expect(splashScreenSpy.hide).toHaveBeenCalled();
console.log("Tests have completed execution!");
return of(null)
});
});
组件 typescript :
constructor(...) {
this.initializeApp();
}
initializeApp() {
// Check session already setup
this.platform.ready()
.then(() => this.store.dispatch(new CheckSessionAction(this)))
.then(() => {
/** StatusBar and SplashScreen is only for Mobile Devices */
console.log("isMobileDevice: " + this.helper.isMobileDevice());
if (this.helper.isMobileDevice()) {
this.statusBar.styleDefault();
this.splashScreen.hide();
}
console.log("Initialization has completed execution");
});
}
console.logs 按以下顺序打印:
测试已完成执行
isMobileDevice:true
初始化已执行完毕
最佳答案
您应该将 initializeApp
函数调用放在 ngOnInit
生命周期 Hook 中。这是调用电话的更好方式。然后在测试中您无需担心构造函数会进行这样的调用。
此外,如果您需要处理异步调用,则可以将测试包装在 async
或 fakeAsync
和 tick
中使测试等待调用完成。这些可以从 Angular 测试库导入。
关于angular - 如何阻止构造函数内部的异步回调进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56482647/