无法通过玩笑的redux操作访问状态

问题描述 投票:1回答:1

在玩笑的单元测试中调度动作时,我无法获得state

我尝试这样做:

  import configureMockStore from 'redux-mock-store'
import * as React         from 'react'
  import MarginPage         from './index'
  import { Provider }       from 'react-redux'
  import {
  mount,
  }                         from 'enzyme'
import thunk                from 'redux-thunk'

const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)

const state = {
  margin: {
    list: null,
  },
}
  
  it('Should list props are correctly filling', async () => {
    await store.dispatch({
      type: 'SET_MARGIN_LIST',
      payload: [0, 1, 2],
    })

    const wrapper = mount(
      <Provider store={store}>
        <MarginPage />
      </Provider>,
    )

    wrapper.update()

    const actions = store.getActions() // Here I have my state
    // But now I would like to have the updated state list inside getState()
    
    
    console.log(store.getState().margin.list) // return undefined
  })
javascript reactjs jestjs enzyme
1个回答
0
投票

我找到了一个答案,希望在遇到此问题时能对您有所帮助。

我们可以获取上面的代码,然后更新:

import * as React         from 'react'
import MarginPage         from './index'
import { Provider }       from 'react-redux'
import {
  mount,
}                         from 'enzyme'
// @ts-ignore
import store              from '@App/helpers/configureStore' // Finally I prefer use store from my app
import { IAppState } from '@App/reducers' // This line come from interface of typeScript

describe('<MarginPage /> Component', () => {
  it('Should list props are correctly filling', async () => {
    // instanciate component and make the test use async/await
    const wrapper = mount(
      <Provider store={store}>
        <MarginPage />
      </Provider>,
    )

 
    await store.dispatch({
      type: 'SET_MARGIN_LIST',
      payload: MOCK_MARGIN_LIST,
    })

    // Don't forget to force the re-render
    wrapper.update()

    // Now we have access to our store
    const state = (store.getState() as IAppState).margin.list as any

    expect(state.results[0].campaigns_revenue).toEqual(47096.52)
  })
})
© www.soinside.com 2019 - 2024. All rights reserved.