我正在测试我们的反应应用程序的注销功能,我在测试localStorage时遇到了麻烦。我想要做的是在我的单元测试中检查if (value === 'logout')
,这样我就可以有expect
断言来检查localStorage是否有我正在测试的项目,这是我遇到麻烦的地方。如何断言if (value === 'logout')
等于localStorage.removeItem('id_token')
这是我正在测试的.js片段
_handleSelectItem = (event, value) => {
if (value === 'logout') {
const sharedLogic = () => {
localStorage.removeItem('id_token')
window.location = '/' // TODO: find a better way to reset the relay cache
}
const onSuccess = (response) => {
sharedLogic()
}
const onFailure = (transaction) => {
var error = transaction.getError() || new Error('Mutation failed.')
console.error(error)
sharedLogic()
}
this.props.relay.commitUpdate(
new SignOutUserMutation({
viewer: this.props.viewer
}
), {onSuccess, onFailure})
}
}
这是我编写的.spec.js,它并不能完成我想要的工作
if(!global.localStorage) {global.localStorage = {} }
// if(value === 'logout')
describe('(Component) AccountManager | Logout ', () => {
let _component
let _props
let value = 'logout'
// if(value === 'logout')
beforeEach(() => {
_props = {
viewer: {
email: 'joe@example.com'
}
}
_component = shallowRenderWithProps(_props)
sinon.spy(global.localStorage, 'getItem')
sinon.spy(global.localStorage, 'setItem')
sinon.spy(global.localStorage, 'clear')
})
afterEach(() => {
global.localStorage.getItem.restore()
global.localStorage.setItem.restore()
global.localStorage.clear.restore()
})
it('Should check if Logout work correctly', () => {
if(value === 'logout');
console.log(global.localStorage)
expect(global.localStorage.getItem.withArgs('id_token').calledOnce).is.true;
})
注意上面的测试通过,但没有清除指示我应该测试它的CodeCov错误。我刚开始做出反应,所以我很感激帮助我了解更多
答案 0 :(得分:0)
if if (typeof(Storage) !== "undefined" && localStorage.getItem(value) === 'logout') {
//[do your stuff here]
}