diff --git a/packages/happy-dom/src/storage/StorageFactory.ts b/packages/happy-dom/src/storage/StorageFactory.ts index cfdf53506..b7bb4504a 100644 --- a/packages/happy-dom/src/storage/StorageFactory.ts +++ b/packages/happy-dom/src/storage/StorageFactory.ts @@ -41,7 +41,25 @@ export default class StorageFactory { return storage[PropertySymbol.data][key] !== undefined; }, defineProperty(storage: Storage, key: string, descriptor: PropertyDescriptor): boolean { - if (Storage.prototype.hasOwnProperty(key) || descriptor.value === undefined) { + if (Storage.prototype.hasOwnProperty(key)) { + if (descriptor.get || descriptor.set) { + Object.defineProperty(storage, key, { + ...descriptor, + get: descriptor.get ? descriptor.get.bind(storage) : undefined, + set: descriptor.set ? descriptor.set.bind(storage) : undefined + }); + } else { + Object.defineProperty(storage, key, { + ...descriptor, + value: + typeof descriptor.value === 'function' + ? descriptor.value.bind(storage) + : descriptor.value + }); + } + return true; + } + if (descriptor.value === undefined) { return false; } storage[PropertySymbol.data][key] = String(descriptor.value); diff --git a/packages/happy-dom/test/storage/Storage.test.ts b/packages/happy-dom/test/storage/Storage.test.ts index 713ac1b81..cbc5f390a 100644 --- a/packages/happy-dom/test/storage/Storage.test.ts +++ b/packages/happy-dom/test/storage/Storage.test.ts @@ -1,6 +1,6 @@ import Storage from '../../src/storage/Storage.js'; import StorageFactory from '../../src/storage/StorageFactory.js'; -import { beforeEach, describe, it, expect } from 'vitest'; +import { beforeEach, describe, it, expect, vi } from 'vitest'; describe('Storage', () => { let storage: Storage; @@ -140,4 +140,12 @@ describe('Storage', () => { expect(storage['key2']).toBe(undefined); }); }); + + describe('vi.spyOn()', () => { + it('Should spy on a method.', () => { + const spy = vi.spyOn(storage, 'getItem'); + storage.getItem('key1'); + expect(spy).toHaveBeenCalled(); + }); + }); });