How can I resolve a TypeScript error around window.opener?

874 Views Asked by At

Can someone please help in resolving these TypeScript errors. The test runs fine but TypeScript complains in the IDE.

I appear to get two TypeScript errors.

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)

})
1

There are 1 best solutions below

1
Emmanuel Ponnudurai On

The first error is because you are trying to use spyOn on a property. It must only be used on functions. opener returns the reference to the window which opened the current window. More info here https://developer.mozilla.org/en-US/docs/Web/API/Window/opener

You should just mock the opener with some mock variable of your choice.

Secondly, the error you are seeing is expected because typescript prevents you from deleting a non-optional property from an object.

One way to get around it is to do something like this,

// tslint:disable-next-line: no-any
delete (window as any).opener;

However, note that this is only a hack in a unit test environment.

If you do something like this (delete property) in actual app code, it is a signal that you are most probably doing something wrong, and should avoid it, which is the very intent of that error from Typescript.