Why fixture.detectChanges() is required for a unit test [Jasmine/Karma]
From https://angular.io/guide/testing:
You must tell the TestBed to perform data binding by calling fixture.detectChanges().
[...]
Delayed change detection is intentional and useful. It gives the tester an opportunity to inspect and change the state of the component before Angular initiates data binding and calls lifecycle hooks.
Related videos on Youtube
Comments
-
Tanzeel over 1 year
I'm learning Unit testing with Jasmine and Karma. My test case is passing but I do not understand one thing. Here's my typescript:
// array list of objects where each month will have one object i.e. 12 objects (Jan to Dec) monthsData: Array<{ monthName: string; monthYear: number; isInRange: boolean; isLowerEdge: boolean; isUpperEdge: boolean; }>; rangeState: { edge1Exists: boolean; edge2Exists: boolean; edgeIndexes: Array<number> }; initRangeState() {} <---- method which should be called; Not important for this question
And here's my test case in spec file:
it('should re-initialize range state when reflection is triggered', () => { fixture.detectChanges(); <--- why this is required ? const rangeState = { edge1Exists: true, edge2Exists: true, edgeIndexes: [] }; const monthsData = { monthName: 'Jan', monthYear: 2020, isInRange: true, isLowerEdge: true, isUpperEdge: false }; fixture.componentInstance.rangeState = rangeState; fixture.componentInstance.monthsData[0] = monthsData; ... expect(fixture.componentInstance.initRangeState).toHaveBeenCalled(); });
I do not understand that when I passed dummy
rangeState
andmonthsData
already. Then why I need to runfixture.detectChanges()
in first place. My test case is failing without calling that. Please tell me the reason behind it. I'm sure there is something that I don't know. Here's the screenshot whenfixture.detectChanges()
is removed: