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

标签 angular typescript testing ionic-framework jasmine

我目前正在尝试为 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 中。这是调用电话的更好方式。然后在测试中您无需担心构造函数会进行这样的调用。

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

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

相关文章:

javascript - Angular 2 : Component doesn't render

javascript - 如何制作影响 Angular 不同数据的可重用函数?

javascript - 调用 TypeScript 编译器作为 NPM 模块

python - 检查是否使用不同参数多次调用函数

testing - 测试线束软件

javascript - Angular 的循环模板可以通过枚举循环吗?

javascript - 获取匿名对象类型的字符串名称?

reactjs - 是否有强制执行 useState() 类型的 eslint 规则?

json - 在 rxjs ajax 回调中解析 JSON 不起作用

eclipse - JUnit 4 中是否有与 testNG 的 @BeforeSuite 等效的东西?