capricorn86 / happy-dom

A JavaScript implementation of a web browser without its graphical user interface
MIT License
3.14k stars 189 forks source link

Error when adding a spy on localStorage #1377

Closed sybers closed 3 months ago

sybers commented 3 months ago

Describe the bug Hey,

I'm trying to add a spy on localstorage.setItem and I'm getting an error.

I'm using @happy-dom/jest-environment@14.3.9.

To Reproduce

If you add the code below to any tests:

jest.spyOn(localStorage, 'setItem').mockImplementationOnce(() => {
    throw new Error('error');
});

Jest will fail with the following error:

TypeError: 'deleteProperty' on proxy: trap returned falsish for property 'setItem'.

Please let me know if you need more information, Thanks !

PS: This could be related to #1368

capricorn86 commented 3 months ago

Thank you for reporting @sybers! :slightly_smiling_face:

I have fixed the error when deleting a property, but it seems like it will not be possible to spy on the instance methods with Jest (it works with Vitest), as Jest relies on Object.getOwnPropertyDescriptor(), which according to spec should return undefined for the Storage methods.

In the latest version of Happy DOM, I have made it possible to spy on Storage.prototype methods, which should solve your problem.

Example:

jest.spyOn(Storage.prototype, 'getItem').mockImplementationOnce(() => () => {
   throw new Error('error');
});

Read more about the release: https://github.com/capricorn86/happy-dom/releases/tag/v14.6.2

sybers commented 3 months ago

Thanks alot for fixing this @capricorn86 !

In the latest version of Happy DOM, I have made it possible to spy on Storage.prototype methods, which should solve your problem.

That's how I used to to with Jest so everything good :)