惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
MyScale Blog
MyScale Blog
Recent Announcements
Recent Announcements
酷 壳 – CoolShell
酷 壳 – CoolShell
GbyAI
GbyAI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
N
Netflix TechBlog - Medium
V
V2EX
MongoDB | Blog
MongoDB | Blog
Microsoft Security Blog
Microsoft Security Blog
博客园 - 三生石上(FineUI控件)
Stack Overflow Blog
Stack Overflow Blog
U
Unit 42
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
H
Help Net Security
D
DataBreaches.Net
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
T
The Blog of Author Tim Ferriss
C
Check Point Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报

CodeBlocQ

Have Mobx and React work with TypeScript Loose assertions on arguments passed to function with Jest TypeScript Abstract Class Check if a Docker image exists locally A-Star Pathfinding React Demo My Free and Open Source Expense Tracker App is on the App Store Pass artifacts around in between stages in gitlab CI How to start a tech company as a non technical individual Setup gitment on your Hexo blog
Jest - Mock Local Storage
Jonathan Klughertz · 2021-01-08 · via CodeBlocQ

jsdom does not include a fake local storage API, so you need to roll out your own.

Local storage fake

Here is a simple local storage fake

const fakeLocalStorage = (function() {
let store = {};

return {
getItem: function(key) {
return store[key] || null;
},
setItem: function(key, value) {
store[key] = value.toString();
},
removeItem: function(key) {
delete store[key];
},
clear: function() {
store = {};
}
};
})();

Wiring

localStorage is a read-only property of the window interface, so it is not possible to just reassign it like window.localStorage = fakeLocalStorage

Object.defineProperty(window, 'localStorage', {
value: fakeLocalStorage
});

Full working example

Simple function that uses the localStorage API



export function saveToStorage(value) {
window.localStorage.setItem('the-key', value);
}

Corresponding jest test



import { saveToStorage } from './storage';

const fakeLocalStorage = (function () {
let store = {};

return {
getItem: function (key) {
return store[key] || null;
},
setItem: function (key, value) {
store[key] = value.toString();
},
removeItem: function (key) {
delete store[key];
},
clear: function () {
store = {};
}
};
})();

describe('storage', () => {
beforeAll(() => {
Object.defineProperty(window, 'localStorage', {
value: fakeLocalStorage,
});
});

it('saves the key to the storage', () => {
saveToStorage('fake-value');

expect(window.localStorage.getItem('the-key')).toEqual('fake-value');
});
});