我是Redux商店测试的新手。 当我使用Jest测试下面的Redux商店时,我得到了
TypeError:无法读取未定义的属性'redux-store'
TypeError:无法读取未定义的属性“getState”
似乎与Redux有关的东西不起作用。我怎样才能解决这个问题并使该商店测试成功? storeFactory和测试如下所示。
import { createStore, combineReducers, applyMiddleware} from 'redux'
import { colors, sort } from './reducers'
import stateData from '../../data/initialState'
let console = window.console
let localStorage = window.localStorage
const logger = store => next => action => {
let result
console.groupCollapsed("dispatching", action.type)
console.log('prev state', store.getState())
console.log('action', action)
result = next(action)
console.log('next state', store.getState())
console.groupEnd()
return result
}
const saver = store => next => action => {
let result = next(action)
localStorage['redux-store'] = JSON.stringify(store.getState())
return result
}
const storeFactory = (initialState=stateData) =>
applyMiddleware(logger, saver)(createStore)(
combineReducers({colors, sort}),
(localStorage['redux-store']) ?
JSON.parse(localStorage['redux-store']) :
initialState
)
export default storeFactory
import C from '../src/constants'
import storeFactory from '../src/store'
import { addColor } from '../src/actions'
describe("Action Creators", () => {
let store
describe("addColor", () => {
const colors = [
{
id: "8658c1d0-9eda-4a90-95e1-8001e8eb6036",
title: "lawn",
color: "#44ef37",
timestamp: "Mon Apr 11 2016 12:54:19 GMT-0700 (PDT)",
rating: 4
},
{
id: "f9005b4e-975e-433d-a646-79df172e1dbb",
title: "ocean blue",
color: "#0061ff",
timestamp: "Mon Apr 11 2016 12:54:31 GMT-0700 (PDT)",
rating: 2
},
{
id: "58d9caee-6ea6-4d7b-9984-65b145031979",
title: "tomato",
color: "#ff4b47",
timestamp: "Mon Apr 11 2016 12:54:43 GMT-0700 (PDT)",
rating: 0
}
]
beforeAll(() => {
store = storeFactory({colors})
store.dispatch(addColor("Dark Blue", "#000033"))
})
afterAll(() => global.localStorage['redux-store'] = false)
it("should add a new color", () =>
expect(store.getState().colors.length).toBe(4))
it("should add a unique guid id", () =>
expect(store.getState().colors[3].id.length).toBe(36))
it("should set the rating to 0", () =>
expect(store.getState().colors[3].rating).toBe(0))
it("should set timestamp", () =>
expect(store.getState().colors[3].timestamp).toBeDefined())
})
})
答案 0 :(得分:0)
WebAPI localStorage
在Jest上下文中不可用。
您可以通过在项目的根文件夹中声明setupTests.js
文件来模拟它以进行测试。
const localStorageMock = {
getItem: () => jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
要测试与Redux相关的代码,可以参考官方Redux文档中的优秀testing guidelines。
编辑:快速检查后,root用户的setupTests.js文件是create-react-app CLI的一项功能。如果你不使用它可能不会起作用。 但是这个想法仍然存在,jest上下文中没有localStorage。