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

推荐订阅源

V
Visual Studio Blog
博客园 - 司徒正美
博客园_首页
Jina AI
Jina AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
I
InfoQ
M
MIT News - Artificial intelligence
T
Tailwind CSS Blog
L
LangChain Blog
Last Week in AI
Last Week in AI
A
About on SuperTechFans
B
Blog
博客园 - 叶小钗
雷峰网
雷峰网
H
Help Net Security
WordPress大学
WordPress大学
大猫的无限游戏
大猫的无限游戏
博客园 - 【当耐特】
云风的 BLOG
云风的 BLOG
Microsoft Azure Blog
Microsoft Azure Blog
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

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