gpt4 book ai didi

angular - 为什么单元测试需要 fixture.detectChanges() [Jasmine/Karma]

转载 作者:行者123 更新时间:2023-12-04 00:56:32 27 4
gpt4 key购买 nike

我正在用 Jasmine 和 Karma 学习单元测试。我的测试用例正在通过,但我不明白一件事。这是我的 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

这是我在规范文件中的测试用例:
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() 后的屏幕截图:

enter image description here

最佳答案

来自 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.

关于angular - 为什么单元测试需要 fixture.detectChanges() [Jasmine/Karma],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62180812/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com