Search code examples
angularng-bootstrapangular-test

Is it correct to have 2 different "detectChanges" functions?


I was trying to test a modal component, and I did it in this way

const fixture = TestBed.createComponent(Component);
const component = fixture.componentInstance;

but I have a case where I need to test, the navigation too from my modal component.

And I was trying to create route and route components like this

const harness = await RouterTestingHarness.create();
const navigationComponent = await harness.navigateByUrl('', HostTestComponent);

but then I noticed that I have to create my modal too, and now my code looks like this

const harness = await RouterTestingHarness.create();
const navigationComponent = await harness.navigateByUrl('', HostTestComponent);
const fixture = TestBed.createComponent(Component);
const component = fixture.componentInstance;

but, if you noticed, now I will have to different detectChanges functions.

harness.detectChanges();
fixture.detectChanges();

So my question is,

Is there another way to do this, or is it correct to have 2 different detectChanges, once for routing and the other one for my component?


Solution

  • Is it correct to have 2 different detectChanges, once for routing and the other one for my component?

    Yes, exactly! There is no problem in having two calls since they're used for different contexts.

    harness.detectChanges() is specific to the RouterTestingHarness and will trigger change detection for components involved in routing.

    fixture.detectChanges() is specific to the TestBed fixture that you create for your modal component, ensuring that Angular's change detection runs for that component.