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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

How do I collapse sections of code in Visual Studio Code for Windows?