Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why component generated by ng cli has the spec file with 2 beforeeach method?

When I run ng c my-component, I get a spec file that has 2 beforeEach methods.

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

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

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

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

Why do I have 2 beforeEach, do I need both of them? All the tutorial are showing only the second, i.e. the non-asynchronous one. Also code needed to run a basic test is split among those 2 methods. Any reason?

Thanks for helping.

like image 893
Richard77 Avatar asked Sep 04 '18 16:09

Richard77


1 Answers

As compileComponents() is an async function returning a promise the beforeEach is marked with async. So Jasmine knows that everything has to be resolved before moving to the next step (-> here the second beforeEach). The second beforeEach includes synchronous code only so it's not marked with async.

If you put everything in one beforeEach it could happen that compileComponents() is not resolved until createComponent(MyComponent) is called - this could lead to errors but if compileComponents() is fast enough it won't.

like image 83
Peter Sterr Avatar answered Oct 15 '22 11:10

Peter Sterr