无法在React / Redux组件的Jest / Enzyme测试中获得节点

时间:2018-07-24 07:17:51

标签: reactjs unit-testing redux jestjs enzyme

我有一个最简单的测试文件,该文件必须将模拟存储放入组件中,然后在渲染时按className-bannerWrap交还实际的节点。但不幸的是,我总是得到一个不确定的信息。我认为这是将渲染组件放入商店后出现的渲染组件问题。

有什么建议吗?谢谢

测试文件:

import React from 'react'
import { shallow } from 'enzyme'
import configureStore from 'redux-mock-store'
import initialState from './mocks'
import Banners from '../Banners'

describe('<Banners />', () => {
  const mockStore = configureStore()
  const store = mockStore(initialState)
  const Component = shallow(<Banners store={store} />)

  it('should render first banner', () => {
    expect(Component).toMatchSnapshot()
    expect(Component.find('.bannerWrap').length).toBe(1) // undefined
  })
})

快照文件(不是我收到组件的道具的节点):

// Jest Snapshot v1

exports[`<Banners /> should render first banner 1`] = `
<Banners
  bannerID={1}
  dispatch={[Function]}
  store={
    Object {
      "clearActions": [Function],
      "dispatch": [Function],
      "getActions": [Function],
      "getState": [Function],
      "replaceReducer": [Function],
      "subscribe": [Function],
    }
  }
/>
`;

组件:

import React from 'react'
import { connect } from 'react-redux'
import { CSSTransitionGroup } from 'react-transition-group'

const Banners = ({ bannerID }) => {
  return (
    <div className="bannerWrap">
      <CSSTransitionGroup
        transitionName="fade"
        transitionEnterTimeout={ANIMATION_DURATION}
        transitionLeaveTimeout={ANIMATION_DURATION}
      >
        <Banner key={bannerID} />
      </CSSTransitionGroup>
    </div>
  )
}

const mapStateToProps = state => ({
  bannerID: state.search.lastSubID
})

export default connect(mapStateToProps, null)(Banners)

2 个答案:

答案 0 :(得分:2)

问题出在用于组件渲染的Enzyme方法中。如果在组件中使用Redux存储,则需要将组件包装在mount中,而不是shallow中。

只需替换您的测试文件:

import React from 'react'
import { mount } from 'enzyme'
import configureStore from 'redux-mock-store'
import initialState from './mocks'
import Banners from '../Banners'

describe('<Banners />', () => {
  const mockStore = configureStore()
  const store = mockStore(initialState)
  const Component = mount(<Banners store={store} />)

  it('should render first banner', () => {
    expect(Component).toMatchSnapshot()
    expect(Component.find('.bannerWrap').length).toBe(1) // undefined
  })
})

如果您想了解更多信息,请转到链接:Enzyme: When to use shallow, render, or mount?

答案 1 :(得分:0)

您使用的是浅色,因此不会渲染实际的Banners组件,要解决此问题,您可以尝试仅导出Banner组件而不是连接的组件。它将解决您的问题。