谁能帮助解决这些TypeScript错误?测试运行正常,但TypeScript在IDE中报错。
我得到两个TypeScript错误。
test('a test', () => {
Object.defineProperty(window, 'opener', {
value: mockMessage,
configurable: true
})
const spy = jest.spyOn(window.opener, 'postMessage')
//TS Error: No overload matches this call.
//Overload 1 of 4, '(object: {}, method: never): SpyInstance<never, never>', gave the following error.
// Argument of type 'Window | null' is not assignable to parameter of type '{}'.
// Type 'null' is not assignable to type '{}'.
//Overload 2 of 4, '(object: {}, method: never): SpyInstance<never, never>', gave the following error.
// Argument of type 'Window | null' is not assignable to parameter of type '{}'.
// Type 'null' is not assignable to type '{}'.ts(2769)
delete window.opener
//TS Error: The operand of a 'delete' operator must be optional.ts(2790)
})
第一个错误是因为您试图在属性上使用spyOn
。它只能用于函数。Opener返回对打开当前窗口的窗口的引用。更多信息在这里https://developer.mozilla.org/en-US/docs/Web/API/Window/opener
您应该使用您选择的一些模拟变量来模拟opener
。
其次,你看到的错误是意料之中的,因为typescript阻止你从对象中删除非可选属性。
一种绕过它的方法是这样做,// tslint:disable-next-line: no-any
delete (window as any).opener;
但是,请注意,这只是在单元测试环境中的一个hack。
如果你在实际的应用代码中做了这样的事情(delete property),这是一个信号,表明你很可能做错了什么,应该避免它,这是Typescript错误的真正意图。