jeudi 6 juin 2019

How to block on asynchronous callbacks inside of constructors for testing?

I'm currently trying to write tests for ionic. My autogenerated tests are finishing before the asynchronous callback is executed. How can I detect when the callbacks in the constructors are completed so I can run my checks?

Promises are not an option for this because TestBed.createComponent already returns a fixture and cannot return a promise.

If I were to implement a done() callback, I would have to modify the constructor signature to include a callback and this feels like bad practice.

Test File:

  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)
    });
  });

Component 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");
      });
  }

The console.logs print in this order:

Tests have completed execution

isMobileDevice: true

Initialization has completed execution

Aucun commentaire:

Enregistrer un commentaire