Skip to content

Commit

Permalink
fix: [#1377] Makes it possible to spy on Storage.prototype methods
Browse files Browse the repository at this point in the history
  • Loading branch information
capricorn86 committed Apr 6, 2024
1 parent debbd3a commit 64e4a37
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 14 deletions.
15 changes: 2 additions & 13 deletions packages/happy-dom/src/storage/StorageFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,20 @@ export default class StorageFactory {
* Creates a new storage.
*/
public static createStorage(): Storage {
const boundMethods: { [k: string]: (...arg) => any } = {};
const boundGetters: { [k: string]: () => any } = {};

// Documentation for Proxy:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
return new Proxy(new Storage(), {
get(storage: Storage, key: string): string | number | boolean | Function {
if (Storage.prototype.hasOwnProperty(key)) {
if (boundMethods[key] !== undefined) {
return boundMethods[key];
}
if (boundGetters[key] !== undefined) {
return boundGetters[key]();
}
const descriptor = Object.getOwnPropertyDescriptor(Storage.prototype, key);
if (descriptor.value !== undefined) {
if (typeof descriptor.value === 'function') {
boundMethods[key] = storage[key].bind(storage);
return boundMethods[key];
return storage[key].bind(storage);
}
return descriptor.value;
}
if (descriptor.get) {
boundGetters[key] = descriptor.get.bind(storage);
return boundGetters[key]();
return descriptor.get.call(storage);
}
return storage[key];
}
Expand Down
2 changes: 1 addition & 1 deletion packages/happy-dom/test/storage/Storage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ describe('Storage', () => {
});

it('Should be able to spy on prototype methods.', () => {
Storage.prototype.getItem = vi.fn(() => 'mocked');
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => 'mocked');

expect(storage.getItem('key1')).toBe('mocked');
});
Expand Down

0 comments on commit 64e4a37

Please sign in to comment.