【问题标题】:Cannot initialize Redux mock store无法初始化 Redux 模拟存储
【发布时间】:2018-07-04 14:56:33
【问题描述】:

我正在尝试根据文档使用redux-mock-store

import React from 'react'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import configureStore from 'redux-mock-store'

import App from '.'
import rootReducer from '../../store/reducers'

Enzyme.configure({ adapter: new Adapter() })

describe('The App container', () => {
    let store
    const mockStore = configureStore()

    beforeEach(() => store = mockStore(rootReducer))

    it('renders without crashing', () => {
        const tree = Enzyme.shallow(<App store={store} />)
        expect(tree).toMatchSnapshot()
    })
})

问题是,我收到以下错误:

reducer 收到的先前状态是意外类型。预期参数是 Immutable.Collection 或 Immutable.Record 的实例,具有以下属性:

还有:

TypeError: inputState.withMutations 不是函数

我不应该包括rootReducer吗?

有没有更好的方法来初始化模拟商店?


编辑:我也试过用initialState来开店,但不行:

import React from 'react'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import configureStore from 'redux-mock-store'

import App from '.'

Enzyme.configure({ adapter: new Adapter() })

describe('The App container', () => {
    let store
    const mockStore = configureStore()
    const initialState = {}

    beforeEach(() => store = mockStore(initialState))

    it('renders without crashing', () => {
        const tree = Enzyme.shallow(<App store={store} />)
        expect(tree).toMatchSnapshot()
    })
})

● App 容器 › 渲染时不会崩溃

TypeError: state.get 不是函数

【问题讨论】:

  • 查看文档,您不应该传入 initialState 而不是 rootReducer 吗?还是某种物体?
  • 是的,当我尝试使用 initialState 时,我得到了store.getState is not a function

标签: javascript unit-testing redux mocking redux-mock-store


【解决方案1】:

你应该挂载你的组件,包裹在 Provider:

import { Provider } from 'react-redux'

// ...store configuration

const tree = Enzyme.mount(
  <Provider store={store}>
    <App />
  <Provider>
)

// ... assertions

shallow 也有第二个参数用于传递上下文,但我不确定它是否与 redux 存储一起工作。

【讨论】:

  • 很遗憾我没有创建沙盒链接。我不知道这是否能解决我的问题
猜你喜欢
  • 2016-02-03
  • 1970-01-01
  • 2014-09-09
  • 2021-11-03
  • 2014-10-18
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多