Skip to content

Commit

Permalink
Merge pull request #1370 from capricorn86/1368-error-spying-on-sessio…
Browse files Browse the repository at this point in the history
…nstorage

fix: [#1368] Fixes problem with spying on properties in Storage
  • Loading branch information
capricorn86 committed Mar 26, 2024
2 parents 13dee56 + 926ca6f commit 1ad442b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
20 changes: 19 additions & 1 deletion packages/happy-dom/src/storage/StorageFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
10 changes: 9 additions & 1 deletion packages/happy-dom/test/storage/Storage.test.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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();
});
});
});

0 comments on commit 1ad442b

Please sign in to comment.