Difference between ChangeDetectorRef.detectChanges and fixture.detectChanges
Difference between ChangeDetectorRef.detectChanges and fixture.detectChanges
Let's say we have a component - MyComponent with OnPush change detection strategy which injects ChangeDetectorRef in order to manually trigger detectChanges() (for example inside the subscriptions or somewhere else).
MyComponent
OnPush
ChangeDetectorRef
detectChanges()
And we also have a test for this component. So when we get the instance of fixture = TestBed.createComponent(MyComponent) - we can also trigger detectChanges() to perform data binding in our tests.
fixture = TestBed.createComponent(MyComponent)
detectChanges()
My question is - what's the difference between these two methods in both cases? Can we get the same result if I trigger component.changeDetecotrRef.detectChanges() in the tests instead of triggering fixture.detectChanges()?
component.changeDetecotrRef.detectChanges()
fixture.detectChanges()
1 Answer
1
They technically do the same thing, but changeDetecotrRef.detectChanges() is a piece of component functionality while fixture.detectChanges() is a shim for testing.
changeDetecotrRef.detectChanges()
fixture.detectChanges()
The difference is that changeDetecotrRef.detectChanges() triggers change detection in the compiled Angular app, while fixture.detectChanges() triggers change detection in the test environment. The former is designed to work with a fully compiled Angular app, while the latter works with a fixture designed to emulate a full Angular app.
changeDetecotrRef.detectChanges()
fixture.detectChanges()
The #1 rule of unit testing is to not change code to fit a test, so use changeDetecotrRef.detectChanges() in component code when you need change detection in order for the component to function, and use fixture.detectChanges() to shim a test when change detection is expected to happen (which is almost always used for testing UI updates).
changeDetecotrRef.detectChanges()
fixture.detectChanges()
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.