Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 unit test must call whenStable multiple times when nesting ngModel elements

I am well aware of this bug here:

https://github.com/angular/angular/issues/10148

Which mentions the need to call fixture.detectChanges(); then a fixture.whenStable().

However, when I start nesting elements that each makes a usage of the ngModel value accessor provider, I have to call these two methods in a loop.

Is there a different way to do this? It doesn't seem super efficient and I constantly need to edit this function. I could simplify this with a recursive method to prevent duplication, but that's not the question.

export function bugWhenStable(fixture: ComponentFixture<any>): Promise<any> {
    let def = new Promise(resolver => {
        fixture.detectChanges();
        fixture.whenStable().then(() => {
            fixture.detectChanges();
            fixture.whenStable().then(() => {
                fixture.detectChanges();
                fixture.whenStable().then(() => {
                    resolver();
                });
            });
        });
    });

    return def;
}

My components do something like this:

<wm-comp1 [(ngModel)]="value"></wm-comp1>

Which in Comp1 I have

<wm-comp2 [(ngModel)]="value"></wm-comp2>

etc.

like image 721
jsgoupil Avatar asked Oct 18 '22 20:10

jsgoupil


2 Answers

Why not using async/await

it('should do whatever', async(async() => {
  fixture.detectChanges();
  await fixture.whenStable();
}));
like image 161
XciD Avatar answered Oct 21 '22 05:10

XciD


have you tried returning the promise to the the next then fn? this will makeit waits until it gets resolved. I tried it once in my specs and worked perfectly. looks cleaner.

export function bugWhenStable(fixture: ComponentFixture<any>): Promise<any> {
  let def = new Promise(resolver => {
    fixture.detectChanges();
    fixture.whenStable()
      .then(() => {
        fixture.detectChanges();

        return fixture.whenStable();
      }).then(() => {
        fixture.detectChanges();

        return fixture.whenStable()
      }).then(() => {
        resolver();
      });
  });

  return def;
}

Also some people doing it like, but I never tried that.

export function bugWhenStable(fixture: ComponentFixture<any>): Promise<any> {
  let def = new Promise(resolver => {
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    tick();
    resolver();
  });
});

return def;
}
like image 35
alaasdk Avatar answered Oct 21 '22 05:10

alaasdk