2

测试组件有问题。我有一个Voting渲染组件的Vote组件,该Vote组件渲染两个<button>标签。使用 mocha+chai 和 react-dom/test-utils 库,渲染到 jsdom,我想测试两个按钮是否被渲染。当我调用 时scryRenderedDOMComponentsWithTag(component, 'button'),传入子 Vote 组件,它返回一个带有两个按钮的集合,但如果我传递父组件(见下文),它返回空。我玩过其他scryRenderedDOMComponentsWith*方法和相同的结果。浏览器中的视觉检查显示按钮肯定正在呈现。scryRenderedDOMComponentsWith*函数不会向下遍历到componentTreearg的子代吗?还是我做错了什么?

投票.js

import React  from 'react'
import Vote   from './Vote'

const Voting = (props) => (
    <div>
      {
        <Vote {...props} />
      }
    </div>
)

export default Voting

投票.js

import React from 'react'

class Vote extends React.Component {

  render() {
    return(
      <div className="voting">
        { this.props.pair.map(entry =>
          <button
            key={ entry }
          >
            <h1>{ entry }</h1>
          </button>
        )}
      </div>
    )
  }
}

export default Vote

投票.spec.js

import React                  from 'react'
import ReactDOM               from 'react-dom'
import {
  renderIntoDocument,
  scryRenderedDOMComponentsWithTag,
  Simulate
}                             from 'react-dom/test-utils'

import { expect }             from 'chai'

import Voting                 from './Voting'

describe('Voting', () => {
  it('renders a pair of buttons', () => {
    const component = renderIntoDocument(
      <Voting pair={["Trainspotting", "28 Days Later"]} />
    )

    const buttons = scryRenderedDOMComponentsWithTag(component, 'button')

    expect(buttons.length).to.equal(2)
  })
})

测试输出

1) Voting
   renders a pair of buttons:

  AssertionError: expected 0 to equal 2
  + expected - actual

  -0
  +2

仅供参考,这是基于全栈 Redux 教程(http://teropa.info/blog/2015/09/10/full-stack-redux-tutorial.html),我一直在按照需要进行更改以使用当前的 API、模式和库。我已删除逻辑以简化此处的代码。在教程示例中,父投票组件通过renderIntoDocument. scryRenderedDOMComponentsWithTag在示例测试中将父Voting组件作为其componentTreearg,并找到由子组件呈现的按钮Vote- 所以我期望它在探查时应该遍历嵌套组件。

4

0 回答 0