Angular Unit Testing - With two beforeEach() methods (one sync and one async), will they always execute/resolve in the correct order?

Viewed 773

my question is basically, are these two code blocks functionally equivalent?

Current set up:

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [MyComponent],
        imports: [...],
        providers: [...]
      })
        .compileComponents();
    }));
  
    beforeEach(() => {
      fixture = TestBed.createComponent(MyComponent);
      component = fixture.componentInstance;
    });

Alternate set up:

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [MyComponent],
        imports: [...],
        providers: [...]
      })
        .compileComponents()
        .then(() => {
           fixture = TestBed.createComponent(MyComponent);
           component = fixture.componentInstance;
         });
      }));

I have run into some problems in tests where a @ViewChild reference to a MatPaginator in the component will sometimes be undefined when running the tests.

I'm wondering if the synchronous function is sometimes executing before the async function completes and the component is fully compiled. Is that possible?

For reference, here is the test that was failing randomly:

    it('should correctly generate the true index of status dropdown elements when the paginator exists', () => {
      component.paginator.pageSize = 10;
      component.paginator.pageIndex = 3;
      const trueIndex = component.getTrueIndex(5);
      expect(trueIndex).toBe(35);
    });
// sometimes got Error: cannot set property pageSize of undefined

And its definition in the component.ts file:

export class MyComponent extends BaseComponent implements OnInit {
  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  ...
}
0 Answers
Related