如何在Chai的单元测试中使用localStorage [英] How to use localStorage in unit tests with Chai

查看:73
本文介绍了如何在Chai的单元测试中使用localStorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有react和redux的应用程序.我的测试引擎是-

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆