Last active
August 1, 2020 09:03
-
-
Save sanusart/c1558845350cc8d8cafbe3c903d46afc to your computer and use it in GitHub Desktop.
Jest mock localStorage #test #jest
This file contains hidden or 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
// ./__mocks__/localStorage.js | |
let mockStorage = {}; | |
module.exports = window.localStorage = { | |
setItem: (key, val) => Object.assign(mockStorage, {[key]: val}), | |
getItem: (key) => mockStorage[key], | |
clear: () => mockStorage = {} | |
}; | |
// Then import it in the reducer test file | |
import '../__mocks__/localStorage'; |
@krey3ix line 11 has instructions. Just import it like import '../__mocks__/localStorage';
and it sets window.localStorage automatically. I guess you could do something like:
let mockStorage = {};
const localStorage = {
setItem: (key, val) => Object.assign(mockStorage, {
[key]: val
}),
getItem: (key) => mockStorage[key],
clear: () => mockStorage = {}
};
export default localStorage;
Then
const localStorage = import '../__mocks__/localStorage';
global.localStorage = localStorage;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, can you give me a little insight on the usage? Like in the .test.js file, do we have to initialize anything or code something?