如何在 Chai 的单元测试中使用 localStorage [英] How to use localStorage in unit tests with Chai
问题描述
我有一个带有 react 和 redux 的应用程序.我的测试引擎是 - Chai
I have an app with react and redux. My test engine is - Chai
在我的减速器 (src/my_reducer.js) 中,我尝试像这样从 localStorage 获取令牌:
In my reducer (src/my_reducer.js), I try to get token from localStorage like this:
const initialState = {
profile: {},
token: window.localStorage.getItem('id_token') ? window.localStorage.getItem('id_token') : null,
}
在我的测试文件 (test/reducer_spec.js) 中,我在测试用例之前导入了my_reducer":
In my tests file (test/reducer_spec.js) I have import 'my_reducer' before test cases:
import myReducer from '../src/my_reducer'
如果我尝试运行测试 - localStorage(或 window.localStorage) - 未定义,则会出现错误.
And I have an error, if I try to run test - localStorage (or window.localStorage) - undefined.
我需要模拟 localStorage 吗?如果我需要,它的位置在哪里?
I need to mock localStorage? If I need, where is the place for it?
推荐答案
我用 解决问题模拟本地存储我的运行测试命令是:
I solve problem with mock-local-storage My run test command is:
mocha -r mock-local-storage --compilers js:babel-core/register --recursive
这篇关于如何在 Chai 的单元测试中使用 localStorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!