jest-location-mock icon indicating copy to clipboard operation
jest-location-mock copied to clipboard

Workaround for newer jsdom

Open zfLQ2qx2 opened this issue 8 months ago • 1 comments

Credit to ChatGPT for this, a workaround for newer jsdom where they make everything immutable, maybe this can get incorporated into your module

function mockLocation(windowObj) {
  const propertyDescriptors = Object.getOwnPropertyDescriptors(windowObj);
  for (const key in propertyDescriptors) {
    propertyDescriptors[key].configurable = true;
  }
  const clonedWindow = Object.defineProperties({}, propertyDescriptors);

  clonedWindow.Event = windowObj.Event;

  let hrefValue = '';

  Object.defineProperty(clonedWindow, 'location', {
    configurable: true,
    value: {
      get href() { return hrefValue; },
      set href(href) { hrefValue = href; }
    }
  });

  return clonedWindow;
}

...

global.window = mockLocation(window)

...

zfLQ2qx2 avatar Jul 03 '24 23:07 zfLQ2qx2