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 spying on sessionStorage #1368

Closed vcmiranda closed 4 months ago

vcmiranda commented 4 months ago

Describe the bug When using spyOn in sessionStorage (vitest), the following message is displayed: 'defineProperty' on proxy: trap returned falsish for property 'getItem'

To Reproduce Sample code

export const useTestFunc = (
  initialValue: string,
  sessionKey: string
): { value: string } => {
  const value = window.sessionStorage.getItem(sessionKey) ?? initialValue;

  return {value};
};

it('should default to session state value when present', () => {
  const sessionKey = 'some:key';
  const getItemSpy = vi.spyOn(sessionStorage, 'getItem');
  sessionStorage.setItem(sessionKey, 'Test value');

  const {
    result: {
      current: {
        value
      },
    },
  } = renderHook(() => useTestFunc('default', sessionKey));

  expect(getItemSpy).toBeCalledWith(sessionKey);
  expect(value).toBe('Test value');
});
vcmiranda commented 4 months ago

That was fast. Thanks.

sybers commented 4 months ago

Hey, I'm trying to add a spy on localstorage.setItem and I'm facing the same issue TypeError: 'deleteProperty' on proxy: trap returned falsish for property 'setItem'.

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

Here's the test code:

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

Thanks !