gpt4 book ai didi

angular - 如何阻止构造函数内部的异步回调进行测试?

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:39 24 4
gpt4 key购买 nike

我目前正在尝试为 ionic 编写测试。我的自动生成测试在执行异步回调之前完成。如何检测构造函数中的回调何时完成以便运行检查?

Promise 不是一个选项,因为 TestBed.createComponent 已经返回一个固定装置并且不能返回一个 promise。

如果我要实现一个 done() 回调,我将不得不修改构造函数签名以包含一个回调,这感觉像是一种糟糕的做法。

测试文件:

  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 按以下顺序打印:

测试已经完成执行

是移动设备:真

初始化已经执行完毕

最佳答案

您应该将 initializeApp 函数调用放在 ngOnInit 生命周期 Hook 中。这是调用此类电话的更好方式。然后在测试中,您无需担心构造函数会像这样进行调用。

此外,如果您有一个需要处理的异步调用,您可以将测试包装在 asyncfakeAsynctick 中让测试等待调用完成。这些可以从 Angular 测试库中导入。

关于angular - 如何阻止构造函数内部的异步回调进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56482647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com