Why fixture.detectChanges() is required for a unit test [Jasmine/Karma]

12,032

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.

Share:
12,032

Related videos on Youtube

Tanzeel
Author by

Tanzeel

Mistake maker and learner.

Updated on October 18, 2022

Comments

  • Tanzeel
    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 and monthsData already. Then why I need to run fixture.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 when fixture.detectChanges() is removed:

    enter image description here