我爲我的ReactJs應用程序(主要是ES6格式)設置了Mocha。運行摩卡給出的錯誤'ReferenceError:sessionStorage未定義'
在運行使用"test": "mocha --compilers js:babel-register --recursive"
設置中的package.json我得到以下輸出測試:
[email protected] ~/workspace/webapp (Test-Setup●●)$ npm test
> [email protected] test /Users/purezen_/workspace/webapp
> mocha --compilers js:babel-register --recursive
/Users/purezen_/workspace/webapp/src/js/data/reducers/auth.js:31
var auth = sessionStorage.getItem('auth');
^
ReferenceError: sessionStorage is not defined
at Object.<anonymous> (auth.js:5:14)
at Module._compile (module.js:397:26)
at loader (/Users/purezen_/workspace/kredx-fe/client/node_modules/babel-register/lib/node.js:158:5)
at Object.require.extensions.(anonymous function) [as .js] (/Users/purezen_/workspace/webapp/node_modules/babel-register/lib/node.js:168:7)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (index.js:5:1)
at Module._compile (module.js:397:26)
at loader (/Users/purezen_/workspace/webapp/node_modules/babel-register/lib/node.js:158:5)
測試/動作/ actions.spec.js
import configureMockStore from 'redux-mock-store'
import createSagaMiddleware from 'redux-saga'
import sagas from 'data/sagas'
import nock from 'nock'
import expect from 'expect'
(function (glob) {
function mockStorage() {
var storage = {};
return {
setItem: function(key, value) {
storage[key] = value || '';
},
getItem: function(key) {
return storage[key];
},
removeItem: function(key) {
delete storage[key];
},
get length() {
return Object.keys(storage).length;
},
key: function(i) {
var keys = Object.keys(storage);
return keys[i] || null;
}
};
}
glob.localStorage = mockStorage();
glob.sessionStorage = mockStorage();
}(typeof window !== 'undefined' ? window : global));
const sagaMiddleware = createSagaMiddleware(sagas)
const middlewares = [ sagaMiddleware ]
const mockStore = configureMockStore(middlewares)
// const storeWithMiddleware = applyMiddleware(middlewares)(mockStore)
console.log(mockStore)
我曾嘗試在spec文件中實現模擬會話存儲,但這似乎沒有幫助。
編輯:這是我的auth.js的要求,在意見
import * as c from 'data/constants'
import {Map} from 'immutable'
// Load auth details from session storage
const auth = sessionStorage.getItem('auth');
const defaultState = Map(JSON.parse(auth));
export default function (state=defaultState, action) {
const { type, payload} = action
switch (type) {
case c.SET_AUTH: {
return Map(payload)
}
}
return state;
}
您能否從/Users/purezen_/workspace/webapp/src/js/data/reducers/auth.js職位的代碼: 31 var auth = sessionStorage.getItem('auth'); – 4m1r
@ 4m1r在說明中更新 – purezen