Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'main' of https://github.com/201flaviosilva-labs/javascr…
…ipt-utils into main
- Loading branch information
Showing
2 changed files
with
42 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// Jest - localStorage and sessionStorage | ||
// This simulates the localStorage and sessionStorage in the jest environment | ||
// Based: https://stackoverflow.com/questions/32911630/how-do-i-deal-with-localstorage-in-jest-tests | ||
|
||
/** | ||
* This simulate the localStorage and sessionStorage in the jest environment | ||
* | ||
* @example import "./MockStorage.js"; // only need to do this | ||
* | ||
* @see {@link https://stackoverflow.com/questions/32911630/how-do-i-deal-with-localstorage-in-jest-tests} | ||
*/ | ||
class StorageMock { | ||
constructor() { this.store = {}; } | ||
/** | ||
* Removes all key/value pairs, if there are any. | ||
* | ||
* Dispatches a storage event on Window objects holding an equivalent Storage object. | ||
*/ | ||
clear() { this.store = {}; } | ||
|
||
/** Returns the current value associated with the given key, or null if the given key does not exist. */ | ||
getItem(key) { return this.store[key] || null; } | ||
|
||
/** | ||
* Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously. | ||
* | ||
* Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.) | ||
* | ||
* Dispatches a storage event on Window objects holding an equivalent Storage object. | ||
*/ | ||
setItem(key, value) { this.store[key] = String(value); } | ||
|
||
/** | ||
* Removes the key/value pair with the given key, if a key/value pair with the given key exists. | ||
* | ||
* Dispatches a storage event on Window objects holding an equivalent Storage object. | ||
*/ | ||
removeItem(key) { delete this.store[key]; } | ||
} | ||
global.localStorage = new StorageMock; | ||
global.sessionStorage = new StorageMock; |