如何为嵌套JSON对象中Highcharts的dataLabel.hide()设置Jasmine Spy
看起来你遇到的问题主要是两个:一是未定义的dataLabel变量导致的引用错误,二是嵌套数据结构的访问和断言问题。让我们一步步解决它:
首先分析ReferenceError: dataLabel is not defined的原因:你代码里直接调用了jasmine.spyOn(dataLabel, 'hide'),但dataLabel这个变量从来没被声明或赋值过——它是嵌套在chart.series[0].data数组每个元素里的属性,必须通过正确的路径访问。
方案1:提前创建Spy并关联到对应dataLabel
你可以先创建独立的spy实例,再把它们赋值给每个data项的dataLabel.hide方法,这样后续断言会更清晰,也方便调试:
// 先创建两个带命名的spy实例,方便区分调试 const hideSpy1 = jasmine.createSpy('dataLabelHideSpy1'); const hideSpy2 = jasmine.createSpy('dataLabelHideSpy2'); const chart = { series: [{ data: [ { shapeArgs: { width: 10, height: 10}, dataLabel: { width: 20, height: 20, hide: hideSpy1 } }, { shapeArgs: { width: 10, height: 10}, dataLabel: { width: 20, height: 20, hide: hideSpy2 } } ], type: HighchartsChartType.Column }] } // 触发load事件执行自定义代码 chartMapper().serialize().events.load.bind(chart).call(); // 断言任意一个hide方法被调用 expect(hideSpy1).toHaveBeenCalled(); // 或者检查两个中的任意一个是否被调用 expect(hideSpy1.calls.any() || hideSpy2.calls.any()).toBe(true);
方案2:直接访问嵌套的dataLabel并断言
如果你更倾向于在chart对象定义时直接创建spy,也可以直接通过完整路径访问对应的hide方法进行断言:
const chart = { series: [{ data: [ { shapeArgs: { width: 10, height: 10}, dataLabel: { width: 20, height: 20, hide: jasmine.createSpy() } }, { shapeArgs: { width: 10, height: 10}, dataLabel: { width: 20, height: 20, hide: jasmine.createSpy() } } ], type: HighchartsChartType.Column }] } // 触发load事件 chartMapper().serialize().events.load.bind(chart).call(); // 断言第一个data项的hide被调用 expect(chart.series[0].data[0].dataLabel.hide).toHaveBeenCalled(); // 或者检查第二个 expect(chart.series[0].data[1].dataLabel.hide).toHaveBeenCalled(); // 或者用数组方法检查任意一个被调用 expect( chart.series[0].data.some(item => item.dataLabel.hide.calls.any()) ).toBe(true);
解决“索引不存在”的问题
如果出现索引不存在的错误,你需要确认chartMapper().serialize()处理后,chart.series[0].data的结构是否和你定义的一致。可以在触发load事件前打印chart对象验证:
console.log(chart.series[0].data); // 检查数组是否存在,元素是否包含dataLabel属性
有可能chartMapper在序列化过程中修改了数据结构,比如过滤了某些数据,或者重新组织了series的格式。如果是这种情况,你需要调整访问路径,匹配处理后的实际结构。
内容的提问来源于stack exchange,提问作者theGreenCabbage
相关产品推荐
相关产品推荐

