React-Enzyme测试 - DropDown无法正确渲染

时间:2018-01-11 21:41:27

标签: enzyme react-bootstrap

我有一个React DropDown

import React from 'react'
import PropTypes from 'prop-types'
import {FormGroup, ControlLabel, FormControl} from 'react-bootstrap'

class dropDown extends React.Component {
  static defaultProps = {
    inputValue: '',
    dropdownText: 'Dropdown'
  };
  static propTypes = {
    dropdownText: PropTypes.string.isRequired
  };
  constructor (props) {
    super(props)
    this.state = {inputValue: ''}
  }

  render () {
    return <div>
      <FormGroup controlId="locale-value">
        <ControlLabel>{this.props.dropdownText}</ControlLabel>
        <FormControl componentClass="select" value={this.state.inputValue}>
          <option value="1">1</option>
          <option value="2">2</option>
        </FormControl>
      </FormGroup>
    </div>
  }
}

export default dropDown

我现在正尝试使用Enzyme进行测试

import React from 'react'
import ReactDOM from 'react-dom'
import LocaleDropDown from './LocaleDropDown'
import ReactTestUtils from 'react-dom/test-utils'
import {FormGroup, ControlLabel, FormControl} from 'eui-components'
import { shallow, mount } from 'enzyme'
import renderer from 'react-test-renderer'

/*
 * Verify that the app can be rendered without any fatal errors.
 */
describe('<dropDown/> component', () => {


  it('renders the Select component', () => {
    const div = document.createElement('div')
    const wrapper = ReactDOM.render(<LocaleDropDown />, div)
    console.log(wrapper.find('select').length.to.equal(1));
  });
});

它表示wrapper.find不是函数。

由于我正在渲染,我期待渲染下拉列表并能够访问其中的所有选项。

1 个答案:

答案 0 :(得分:0)

这可能是一个命名问题。您没有显示已定义LocaleDropDown组件的位置。您的第一个文件只导出名为dropDown的组件。

假设第一个文件名为LocaleDropDown,您应该更改测试文件顶部的import语句。

import dropDown from './LocaleDropDown'

对于它的价值,我会使用酶shallow函数来安装组件,看看你是如何导入它的。

您的测试可能类似于:

/*
 * Verify that the app can be rendered without any fatal errors.
 */
describe('<dropDown/> component', () => {
    const dropDown = () => {
        return shallow(<dropDown />);
    }

    it('renders the Select component', () => {
        const select = dropDown().find('select');
        expect(select.length).toEqual(1);
    });
});