如何测试商店单例? [英] How can I test a store singleton?

查看:117
本文介绍了如何测试商店单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在使用redux-mock-store进行单元测试.

I already am implementing unit tests using redux-mock-store.

我想在使用商店单例的React-native应用程序上执行集成测试套件.但是,即使console.log达到了商店中的reducer功能(似乎正常工作)的状态也不会改变.

I would like to perform an integration test suite on a react-native app that uses store singletons just fine. However even though console.logs reach so far as the reducer function (and seems to be working correctly) state on the store does not change.

// __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 }
}

一切正常,但状态不会改变.如果我通过订阅商店来实现观察者,那么我将看到该动作系列正在分发.

Everything works great, but the state does not change. If I implement an observer by subscribing to the store, I see the action series being dispatched.

推荐答案

我将回答我的问题,以作为其他人研究此因果关系的一种手段.

I'll answer my question as a mean for others to work on this casuistic.

与许多其他教程和指南一样,不鼓励存储单例.我了解的是隔离依赖项和组件的问题.但是,如果您仍然决定像我们一样使用它来使您感到舒适,那么您将需要在其他部门需要时对组件进行模拟,因为它们将不会递归地进行模拟.

As in many other tutorials and guides, store singletons are discouraged. Which I understand is a matter of isolating dependencies and components. However if you still decide to use it for comfort –as we do– you'll need to mock the component when required from other deps, as they are not going to be mocked recursively.

除了具有类似的文件夹结构形式之外,其他形式...

So apart form having a similar to this, folder structure...

.
├── app
|    ├── __mocks__
|    |    |
|    |    └── store.js
|    └── store.js

对于需要同时使用"./store.js"的部门,您需要导出模拟版本.

You'll need to export the mocked version, for those deps that require './store.js' at the same time.

// app/store.js

// Choose mock dependency over current store for tests
if (process.env.NODE_ENV === 'test') {
  jest.mock('./store')
}

这样,每当测试期间需要store.js时,它将递归地选择模拟版本而不是真实版本.

This way, whenever store.js is required during tests, it will recursively choose the mock version over the real one.

存储单例可能需要更多的倡导才能被选为主流的Redux实践.不应被视为反模式.

Probably store singletons need a little more advocacy to be chosen as a mainstream redux practice. Should not be considered an anti-pattern.

这篇关于如何测试商店单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆