仅仅为了测试而创建不同的商店是错误的吗?
Is it wrong to create a different store just for testing?
我想创建 sagas + reducers + actions 的集成测试,但是我能看到的所有关于测试 redux 的文档都使用 redux-mock-store
函数。
import configureMockStore from 'redux-mock-store'
有人可以解释为什么会这样吗?为什么不使用完整的商店?
谢谢
如果此对象是仅为测试目的而创建的 Redux 存储的副本,则创建用于测试的完整 redux 存储并没有错误。如果您创建的模拟商店不是 redux 商店的准确副本,那将是错误的。
redux-mock-store 的主要优点是可以更轻松地测试异步 Redux 操作和中间件。
正如 Dan Abramov 在测试调用 api -
的异步 redux 操作时所说的那样
For async action creators using Redux Thunk or other middleware, it’s
best to completely mock the Redux store for tests. You can still use
applyMiddleware() with a mock store, as shown below (you can find the
following code in redux-mock-store). You can also use nock to mock the
HTTP requests.
库的一个非常有用的部分api能够获取已调度的历史操作数组。
store.getActions() => actions: Array
这对于测试将在一段时间内分派多个操作的异步操作特别有用。
取自文档的示例:
// Test example with mocha and expect
it('should dispatch action', () => {
const initialState = {}
const addTodo = { type: 'ADD_TODO' }
const store = mockStore(initialState)
store.dispatch(addTodo)
const actions = store.getActions()
expect(actions).toEqual([addTodo])
});
我想创建 sagas + reducers + actions 的集成测试,但是我能看到的所有关于测试 redux 的文档都使用 redux-mock-store
函数。
import configureMockStore from 'redux-mock-store'
有人可以解释为什么会这样吗?为什么不使用完整的商店?
谢谢
如果此对象是仅为测试目的而创建的 Redux 存储的副本,则创建用于测试的完整 redux 存储并没有错误。如果您创建的模拟商店不是 redux 商店的准确副本,那将是错误的。
redux-mock-store 的主要优点是可以更轻松地测试异步 Redux 操作和中间件。
正如 Dan Abramov 在测试调用 api -
的异步 redux 操作时所说的那样For async action creators using Redux Thunk or other middleware, it’s best to completely mock the Redux store for tests. You can still use applyMiddleware() with a mock store, as shown below (you can find the following code in redux-mock-store). You can also use nock to mock the HTTP requests.
库的一个非常有用的部分api能够获取已调度的历史操作数组。
store.getActions() => actions: Array
这对于测试将在一段时间内分派多个操作的异步操作特别有用。
取自文档的示例:
// Test example with mocha and expect
it('should dispatch action', () => {
const initialState = {}
const addTodo = { type: 'ADD_TODO' }
const store = mockStore(initialState)
store.dispatch(addTodo)
const actions = store.getActions()
expect(actions).toEqual([addTodo])
});