【问题标题】:Why fixture.detectChanges() is required for a unit test [Jasmine/Karma]为什么单元测试需要fixture.detectChanges() [Jasmine/Karma]
【发布时间】:2020-06-03 19:08:40
【问题描述】:

我正在学习 Jasmine 和 Karma 的单元测试。我的测试用例通过了,但我不明白一件事。这是我的打字稿:

// 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

这是我在规范文件中的测试用例:

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();
});

我不明白当我已经通过虚拟rangeStatemonthsData 时。那为什么我首先需要运行fixture.detectChanges()。我的测试用例没有调用就失败了。请告诉我背后的原因。我确定有一些我不知道的事情。 这是fixture.detectChanges()被删除时的截图:

【问题讨论】:

    标签: angular unit-testing karma-jasmine


    【解决方案1】:

    来自https://angular.io/guide/testing

    您必须通过调用来告诉 TestBed 执行数据绑定 fixture.detectChanges().

    [...]

    延迟更改检测是有意且有用的。它给出了 测试人员有机会检查和更改组件的状态 在 Angular 启动数据绑定和调用生命周期钩子之前。

    【讨论】:

      猜你喜欢
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多