我正在尝试使用sinon测试localStorage
。基本上我对单元测试很新,所以这可能是非常基础的。
更新
我设法提出了这个问题,但现在却给了我一个新的错误Should wrap property of object
测试
describe('Initial State', () => {
it('should set the initial state for the component', () => {
const props = {
currentUser: {}
};
sinon.stub(window.localStorage, 'setItem');
window.localStorage.setItem('none', 'nothing');
});
});
答案 0 :(得分:2)
您可以在所有测试中使用babel-plugin-rewire将mockStorage替换为模拟版本。
这就是我使用它的方式:
import {unauth, signOut, __RewireAPI__} from 'modules/auth/actions';
const rewrite = __RewireAPI__.__Rewire__;
const local = {}; // object where you store all values localStorage needs to return
const storage = {
get(key) {
return local[key];
},
set: sinon.spy(),
remove: sinon.spy()
};
rewrite('storage', storage); // rewrite storage package with your mocked version
// in you test add values you want to get from localStorage
local.credentials = constants.CREDENTIALS;
local.authToken = constants.TOKEN;