skip to content
Alvin Lucillo

Component bindings and asyncs in ng test

/ 1 min read

💻 Tech

In your Angular tests, it’s important that the component you’re testing has its bindings and DOM updated accordingly after initializing the data. For that, you can use detectChanges() before each test.

Another thing is if you have asynchronous operations in your component, you may want to resolve them first. If your component requires some time to resolve asynchronous operations, you can use whenStable(). Note that you need to mock the providers used by your asychronous calls and resolve them before testing the component.

beforeEach(async () => {
    component = TestBed.createComponent(Component1).componentInstance;
});

//...

it('should initialize components', () => {
    component.detectChanges(); // Initial change detection
});

it('should initialize components after sync ops', async () => {
    await fixture.whenStable(); // Wait for all async tasks to complete
});