evelynhathaway / jest-location-mock

🗺🧪 Jest hooks for JSDOM location mock
https://npmjs.com/package/jest-location-mock
MIT License
58 stars 5 forks source link

Workaround for newer jsdom #184

Closed zfLQ2qx2 closed 3 days ago

zfLQ2qx2 commented 2 weeks ago

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

[!WARNING]
Content warning added by a maintainer: This code is generated by GenAI and should not be used without understanding what it does. It is not related to jest-location-mock. Learn more

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)

...
evelynhathaway commented 2 weeks ago

Can you provide the JSDOM version that is not working, the errors or behavior you experience, and a reproduction? This package already does something similar, so I am not sure what issue you may be experiencing that would lead you to generate this code.

evelynhathaway commented 3 days ago

I cannot reproduce this issue, and cannot without any further information.

If anyone runs across this thread, please report the issue you are experiencing with JSDOM, Jest, and jest-location-mock versions, and I will reopen. Do no use code you don't understand like the output from ChatGPT. The code provided is a lower quality workaround for mocking window.location and is incompatible with jest-location-mock.