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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With