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

推荐订阅源

T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
雷峰网
雷峰网
量子位
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
博客园 - Franky
罗磊的独立博客
宝玉的分享
宝玉的分享
博客园_首页
腾讯CDC
The GitHub Blog
The GitHub Blog
D
DataBreaches.Net
IT之家
IT之家
D
Docker
Microsoft Security Blog
Microsoft Security Blog
博客园 - 司徒正美
V
V2EX
月光博客
月光博客
N
Netflix TechBlog - Medium
爱范儿
爱范儿
I
InfoQ
P
Proofpoint News Feed

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');
});
});