Search code examples
angularjasminekarma-jasmineangular-testtestbed

Async beforeEach finished before/after each test unit(it)


I am using Angular 6 and I have one concern regarding every test which I have seen so far.

Here's a simple test of simple component which is generated by cli.

describe('CompComponent', () => {
  let component: CompComponent;
  let fixture: ComponentFixture<CompComponent>;
    
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CompComponent ]
    })
    .compileComponents();
  }));
    
  beforeEach(() => {
    fixture = TestBed.createComponent(CompComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
    
  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

How do I know for certain that each Async beforeEach call is done before each test unit?

Are there any cases where this call will happen after each because test is an async call after all?


Solution

  • Each beforeEach will finish before any test begins.

    In your example, compileComponents() is asynchronous. So, we must use async() method in this case.

    for your reference, look to this link: https://github.com/angular/angular-cli/issues/4774

    to be sure that your beforeEach will finish before any test begins, you can try to debug your test by adding this:

    compileComponents().then( result => {
      console.log(result);
    }
    

    You can set a break point at this line: console.log(result); and you will see that it will be executed all time you run your test, so if you set a breakpoint in this console.log' line and another one in your firt ittest, you will see you will never get to the second break point before doing theconsole.log` break point one, that means that we will have to wait for any async call inside the beforeEach before going to any test.

    Another way to see that the beforeEach will all time finish before any test begins is to write your test this way as well:

    beforeEach(async(() => {
      TestBed.configureTestingModule({
      declarations: [ CompComponent ]
    }).compileComponents().then( result => {
        fixture = TestBed.createComponent(CompComponent);
        component = fixture.componentInstance;
      }
    }));
    

    You will see that in any of your test the fixture is already available, doing that way. So you don't need to add another beforeEach to initialize your fixture.

    To understand more, you can refere to this other answer from Stack Overflow:

    angular-2-testing-async-function-call-when-to-use