[英]Difference between ChangeDetectorRef.detectChanges and fixture.detectChanges
比方說,我們有一個組件- MyComponent
與OnPush
變化檢測策略中注入ChangeDetectorRef
以手動觸發detectChanges()
例如訂閱或其他地方內)。
我們也對這個組件進行了測試。 因此,當我們獲得fixture = TestBed.createComponent(MyComponent)
的實例時,我們還可以觸發detectChanges()
在我們的測試中執行數據綁定。
我的問題是 - 在這兩種情況下這兩種方法有什么區別? 如果我在測試中觸發component.changeDetecotrRef.detectChanges()
而不是觸發fixture.detectChanges()
我們能得到相同的結果嗎?
他們在技術上做同樣的事情,但changeDetecotrRef.detectChanges()
是一個組件功能,而fixture.detectChanges()
是用於測試的墊片。
不同之處在於changeDetecotrRef.detectChanges()
在編譯后的 Angular 應用程序中觸發變更檢測,而fixture.detectChanges()
在測試環境中觸發變更檢測。 前者設計用於完全編譯的 Angular 應用程序,而后者用於模擬完整 Angular 應用程序的夾具。
單元測試的 #1 規則是不更改代碼以適合測試,因此當您需要更改檢測以使組件運行時,請在組件代碼中使用changeDetecotrRef.detectChanges()
,並使用fixture.detectChanges()
來填充測試何時發生變更檢測(例如模擬用戶輸入,或者實際上,例如在組件中調用changeDetecotrRef.detectChanges()
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.