11

我有一个父组件和一个子组件,它只是一个“标签”元素。当我单击子元素时,我需要调用父组件中的函数。我希望它被调用,但状态没有改变,当我看到覆盖文件时,函数没有被调用。

**更新:**代码适用于开发。只是单元测试失败了。

这是我的父组件

父.js

export default class Parent extends Component {
  constructor(props) {
   super(props)
   this.state={clickedChild: false}
   this.handleChildClick = this.handleChildClick.bind(this)
  }

  handleChildClick(index) {
    this.setState({clickedChild:true})
  }

  render(){
   const self = this
   return(
    const items = [{'id':1,'text':'hello'},{'id':2,'text':'world'}]
     <div>
       {items.map(function(item,index){
         return <ChildComponent onChildClick ={ self.handleChildClick.bind(null,index)} childItem={item} />
       })}
     </div>
   )}
}

子组件

export default class ChildComponent extends Component {
    constructor(props) { super(props)}

   render(){
    return(
     <label onClick={this.props.onChildClick}>{this.props.childItem.text} </label>
    )
   }
}

单元测试

import chai from 'chai'
import React from 'react'
import ReactDOM from 'react-dom'
import { mount, shallow } from 'enzyme';
import sinon from 'sinon'
import Parent from '../Parent'
import ChildComponent from '../ChildComponent'


let expect = chai.expect
   describe('check click event on child()',()=>{
      it('clicking menu item',()=>{
          const items = [{'id':1,'text':'hello'},{'id':2,'text':'world'}]
          const wrapper = mount(<Parent items={items} />)
          console.log(wrapper.state('clickedChild')) // prints false
          wrapper.find(ChildComponent).last().simulate('click',1)
          // tried the following
          // wrapper.find(ChildComponent).last().simulate('click')

          console.log(wrapper.state('clickedChild'))  // still prints false
        })
    })
4

1 回答 1

9

我将父组件中的绑定更改为

<ChildComponent onChildClick ={() => self.handleChildClick(index)} childItem={item} />

我在父组件中还调用了一个函数,该函数正在调用它的方法。(parent.js)

handleChildClick(index) {
    this.setState({clickedChild:true})
    this.props.handleClick(index) // i had forgotten to see the line.
}

一旦我在我的测试中删除了上面的注释行。一切都按预期工作。

it('clicking menu item', () => {
    const items = [{'id':1,'text':'hello'},{'id':2,'text':'world'}]
    const handleClickStub = sinon.spy()
    const wrapper = mount(<Parent items={items} handleClick={handleClickStub} />)
    console.log(wrapper.state('clickedChild')) // prints false
    wrapper.find(ChildComponent).last().simulate('click')
    expect(handleClickStub.calledOnce).to.be.true // successful
    console.log(wrapper.state('clickedChild'))  // prints true
})
于 2016-05-12T17:19:35.807 回答