我如何测试商店单例?
How can I test a store singleton?
我已经在使用 redux-mock-store
实施单元测试了。
我想在使用商店单例的反应本机应用程序上执行集成测试套件。然而,即使 console.log
s 达到了 reducer 功能(并且似乎工作正常)的程度,store 上的状态也没有改变。
// __tests__/things.js
jest.mock('../app/store')
import 'react-native'
import * as selectors from '../app/selectors'
import * as sagas from '../app/sagas'
import { store } from '../app/store'
describe('Things', () => {
it('should toggle', async () => {
const previousCounter = selectors.count()
await sagas.increment()
expect(store.getState().count).toEqual(previousCounter)
})
})
同时模拟商店实施:
// __mocks__
import { createStore } from 'redux'
import rootReducer from '../reducers'
export const store = createStore(rootReducer, {})
编辑:示例减速器
// app/reducers.js
function rootReducer (state = { count: 0 }, action = {}) {
const count = state.count + 1
return { ...state, count }
}
一切正常,但状态没有改变。如果我通过订阅商店来实现观察者,我会看到正在调度的动作系列。
我会回答我的问题,作为其他人解决这个问题的方法。
与许多其他教程和指南一样,不鼓励存储单例。我的理解是隔离依赖项和组件的问题。但是,如果您仍然决定为了舒适而使用它——就像我们所做的那样——您将需要在其他部门需要时模拟该组件,因为它们不会被递归地模拟。
所以除了具有与此类似的文件夹结构之外...
.
├── app
| ├── __mocks__
| | |
| | └── store.js
| └── store.js
对于那些同时需要 './store.js' 的部门,您需要导出模拟版本。
// app/store.js
// Choose mock dependency over current store for tests
if (process.env.NODE_ENV === 'test') {
jest.mock('./store')
}
这样,只要在测试期间需要store.js
,它就会递归地选择模拟版本而不是真实版本。
可能存储单例需要更多的宣传才能被选为主流的 redux 实践。不应被视为 anti-pattern.
我已经在使用 redux-mock-store
实施单元测试了。
我想在使用商店单例的反应本机应用程序上执行集成测试套件。然而,即使 console.log
s 达到了 reducer 功能(并且似乎工作正常)的程度,store 上的状态也没有改变。
// __tests__/things.js
jest.mock('../app/store')
import 'react-native'
import * as selectors from '../app/selectors'
import * as sagas from '../app/sagas'
import { store } from '../app/store'
describe('Things', () => {
it('should toggle', async () => {
const previousCounter = selectors.count()
await sagas.increment()
expect(store.getState().count).toEqual(previousCounter)
})
})
同时模拟商店实施:
// __mocks__
import { createStore } from 'redux'
import rootReducer from '../reducers'
export const store = createStore(rootReducer, {})
编辑:示例减速器
// app/reducers.js
function rootReducer (state = { count: 0 }, action = {}) {
const count = state.count + 1
return { ...state, count }
}
一切正常,但状态没有改变。如果我通过订阅商店来实现观察者,我会看到正在调度的动作系列。
我会回答我的问题,作为其他人解决这个问题的方法。
与许多其他教程和指南一样,不鼓励存储单例。我的理解是隔离依赖项和组件的问题。但是,如果您仍然决定为了舒适而使用它——就像我们所做的那样——您将需要在其他部门需要时模拟该组件,因为它们不会被递归地模拟。
所以除了具有与此类似的文件夹结构之外...
.
├── app
| ├── __mocks__
| | |
| | └── store.js
| └── store.js
对于那些同时需要 './store.js' 的部门,您需要导出模拟版本。
// app/store.js
// Choose mock dependency over current store for tests
if (process.env.NODE_ENV === 'test') {
jest.mock('./store')
}
这样,只要在测试期间需要store.js
,它就会递归地选择模拟版本而不是真实版本。
可能存储单例需要更多的宣传才能被选为主流的 redux 实践。不应被视为 anti-pattern.