gpt4 book ai didi

javascript - Jest 模拟 window.sessionStorage 的最佳方法是什么

转载 作者:行者123 更新时间:2023-11-29 16:02:05 67 4
gpt4 key购买 nike

下面是一个非常简单的 Jest 单元测试,运行它时,你会得到这样的错误

Cannot spyOn on a primitive value; undefined given

TypeError: Cannot read property 'getItem' of undefined

但根据this post的最后两条评论, localStorage 和 sessionStorage 已经添加到最新的 JSDOM 和 jest 中。如果使用 jest-localstorage-mock并将它添加到我的 jest setupFiles 然后你会看到像

这样的奇怪错误

TypeError: object[methodName].mockImplementation is not a function

所以我的问题是 Jest 模拟 localStorage/sessionStorage 的最佳方式是什么。谢谢

describe('window.sessionStorage', () => {
let mockSessionStorage;
beforeEach(() => {
mockSessionStorage = {};
jest.spyOn(window.sessionStorage, "getItem").mockImplementation(key => {
return mockSessionStorage[key];
});
});

describe('getItem-', () => {
beforeEach(() => {
mockSessionStorage = {
foo: 'bar',
}
});

it('gets string item', () => {
const ret = window.sessionStorage.getItem('foo');
expect(ret).toBe('bar');
});
});
});

下面是我的jest配置

module.exports = {
verbose: true,
//setupFiles: ["jest-localstorage-mock"],
testURL: "http://localhost/"
};

最佳答案

这里的解决方案只使用jestjstypescript,仅此而已。

index.ts:

export function getUserInfo() {
const userInfo = window.sessionStorage.getItem('userInfo');
if (userInfo) {
return JSON.parse(userInfo);
}
return {};
}

index.spec.ts:

import { getUserInfo } from './';

const localStorageMock = (() => {
let store = {};

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

Object.defineProperty(window, 'sessionStorage', {
value: localStorageMock
});

describe('getUserInfo', () => {
beforeEach(() => {
window.sessionStorage.clear();
jest.restoreAllMocks();
});
it('should get user info from session storage', () => {
const getItemSpy = jest.spyOn(window.sessionStorage, 'getItem');
window.sessionStorage.setItem('userInfo', JSON.stringify({ userId: 1, userEmail: 'example@gmail.com' }));
const actualValue = getUserInfo();
expect(actualValue).toEqual({ userId: 1, userEmail: 'example@gmail.com' });
expect(getItemSpy).toBeCalledWith('userInfo');
});

it('should get empty object if no user info in session storage', () => {
const getItemSpy = jest.spyOn(window.sessionStorage, 'getItem');
const actualValue = getUserInfo();
expect(actualValue).toEqual({});
expect(window.sessionStorage.getItem).toBeCalledWith('userInfo');
expect(getItemSpy).toBeCalledWith('userInfo');
});
});

具有 100% 覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/51566816/index.spec.ts
getUserInfo
✓ should get user info from session storage (6ms)
✓ should get empty object if no user info in session storage (1ms)

----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 4.548s, estimated 6s

这是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/51566816

关于javascript - Jest 模拟 window.sessionStorage 的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566816/

67 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com