lundi 24 septembre 2018

Angular 6 - promise in lifecycle hooks makes other test fail

I have a problem with angular test. I dont know if it is a bug or if i am doing something wrong.

I have 2 components. One that uses promises in ngOnInit and one that is completely empty.

The component using promises looks like this:

import {Component, OnInit} from '@angular/core';
import {User, UserManager} from 'oidc-client';

@Component({
  selector: 'app-test',
  templateUrl: './test-promise.component.html',
  styleUrls: ['./test-promise.component.css']
})
export class TestPromiseComponent implements OnInit {
  private readonly userManager: UserManager;

  public async ngOnInit(): Promise<any> {
    return this.getDataStore('', '', '');
  }

  public getDataStore(url: string, key: string, keyType: string): Promise<any> {

    return this.getToken();
  }

  public getToken(): Promise<string> {

    return this.getUser().then(user => {
      return user.access_token;
    });
  }

  public getUser(): Promise<User> {

    return this.userManager.getUser();
  }
}

In the import statements, you can see what dependencies I have and that I use an Oidc Client.

My other component looks like this(just empty):

import { Component } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent {

}

The test spec for both components just follow the standard spec when you create a new component, so like this for the component that uses promises:

describe('TestPromiseComponent', () => {
  let component: TestPromiseComponent;
  let fixture: ComponentFixture<TestPromiseComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        TestPromiseComponent
      ]
    }).compileComponents().then();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestPromiseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  fit('should create', () => {
    expect(component).toBeTruthy();
  });
});

That is my setup. The very strange thing now is that when I run the test then the TestComponent fails - even though it is the TestPromiseComponent that actually fails. See the results here:

TestComponent fails even though TestPromiseComponent is the one failing

So now for the big question: Why does TestComponent fail even though it is actually TestPromiseComponent that fails?

Can anyone explain that to me :)

Aucun commentaire:

Enregistrer un commentaire