如何使用Sinon对LocalStorage进行单元测试 [英] How to unit test localStorage using sinon
问题描述
我正在尝试使用sinon测试localStorage
.基本上,我是单元测试的新手,所以这可能很基础.
I am trying to test localStorage
using sinon. Basically I am very new to unit testing so this might be very basic.
更新
我设法解决了这个问题,但是现在它给了我一个新的错误Should wrap property of object
I managed to come up with this but now its giving me a new error 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');
});
});
推荐答案
我设法解决了它.感谢@anoop,因为他的回答很有帮助,但是我不得不使用一个主要的变通办法来管理它.
我正在使用 jsdom ,目前它不不支持localStorage
.我在jsdom配置中添加了伪造品.
I managed to resolve it. Thanks to @anoop because his answer was of help but I had to manage it with a major workaround.
I am using jsdom and it currently DOES NOT support localStorage
. I added a fake in my jsdom configuration.
if (!global.window.localStorage) {
global.window.localStorage = {
getItem() { return '{}'; },
setItem() {}
};
}
并通过以下方式对其进行断言:
And asserted it with:
it('should fetch from local storage', () => {
const props = {
currentUser: 'UMAIR',
user: {
is_key: false
}
};
const spy = sinon.spy(global.window.localStorage, "setItem");
spy(props);
expect(spy.calledWith( {
currentUser: 'UMAIR',
user: {
is_key: false
}
}));
spy.restore();
const stub = sinon.stub(global.window.localStorage, 'getItem');
stub(props);
expect(stub.calledWith(Object.keys(props)));
// stub.restore();
});
另请参阅: 如何在JavaScript单元测试中模拟localStorage?
https://github.com/gor181/webpack-react-babel-mocha-boilerplate/tree/master/test/utils
一周前,我还在Sinon
中发现了与此相关的内部问题,但已解决.
I also found an internal issue in Sinon
a week ago related to this but that has been resolved.
请参阅: https://github.com/sinonjs/sinon/issues/1129
希望这对某人有帮助.
这篇关于如何使用Sinon对LocalStorage进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!