我正在尝试模拟 Excel 的命名范围数组,以便我可以运行一些关于添加和删除自定义范围的测试,但似乎模拟对象不具备处理数组的能力?
在 Angular 中使用 Jest。
根据文档,我正在模拟 Host 对象并将其分配给 global.Excel
it('should delete the first item', async () => {
const workbookWithNamedRanges = {
context: {
workbook: {
names: {
items: [
{
name: 'Test 1',
type: 'Error'
},
{
name: 'Test 2',
type: 'Error'
},
]
}
}
},
run: async function (callback: any) {
await callback(this.context);
}
};
const excelMock = new OfficeMockObject(workbookWithNamedRanges) as any;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.Excel = excelMock;
await service.service.removeFirstItem();
expect(excelMock.context.workbook.names.items.length).toBe(1);
});
});
然后为我服务
async removeFirstItem(): Promise<void> {
await Excel.run<void>(async context => {
workbook = context.workbook;
const namedRanges: Excel.NamedItemCollection = workbook.names.load() // <- Error here at .load;
await context.sync();
namedRanges.items.at(0)?.delete();
await context.sync();
});
}
但是.load上出现以下错误
Cannot convert undefined or null to object
TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
我还尝试从 workbook.names.load() 更改为 context.load(workbook.names, 'items') 这产生了不同的错误:
Error: Property _properties needs to be present in object model before load is called.
at C:\Users\User\Addins\addins\node_modules\office-addin-mock\src\officeMockObject.ts:168:15
at Array.forEach (<anonymous>)
at OfficeMockObject.parseObjectPropertyIntoArray (C:\Users\User\Addins\addins\node_modules\office-addin-mock\src\officeMockObject.ts:148:29)
at OfficeMockObject.load (C:\Users\User\Addins\addins\node_modules\office-addin-mock\src\officeMockObject.ts:41:25)
然后我也尝试了 workbook.names.load('items') 但这产生了意外的行为,它可以工作,但 workbook.names.items 未定义,即使它已明确定义。
值得注意的是,该代码适用于上述所有 3 种方法,就像在正常的加载项环境中一样。
有什么建议吗?
尝试更改服务代码以在工作簿对象上调用 .load() 而不是 workbook.names 集合:
await Excel.run<void>(async context => {
context.workbook.load('names');
await context.sync();
context.workbook.names.items.at(0)?.delete();
});
看起来 OfficeMockObject 尚不支持集合,这意味着加载方法未添加到您提供的名称数组中。建议的服务代码可以解决该限制。
您可以在模拟上模拟加载函数:
const workbookWithNamedRanges = {
context: {
workbook: {
names: {
items: [
{
name: 'Test 1',
type: 'Error'
},
{
name: 'Test 2',
type: 'Error'
},
],
load: function() {
return this;
}
}
}
},
run: async function (callback: any) {
await callback(this.context);
}