【问题标题】:React : test a function which is passed as a props and is triggered by the parentReact : 测试一个作为 props 传递并由父级触发的函数
【发布时间】:2018-03-08 15:53:55
【问题描述】:

我正在尝试为我的测试触发点击事件。就像这样:

describe('Button', function() {
      test('is clicked when player two is pending', (props ={}) => {
        const mockRandomAdv = sinon.spy();

         const tree = shallow(
            <FightButton  
                        button="Random adversary"
                        isPlayerTwoPending={true}
                        isPlayerOnePending={false}
                        onClick={mockRandomAdv}

             />
        );

       tree.find('Button').simulate('click');
       //expect(mockRandomAdv.calledOnce).toEqual(true);

        console.log(tree.props().children.onClick)
        //.not.toBe('fight-button random');
    });
});

第一个期望返回 false,因此不会触发点击。 当我 console.log() 它返回未定义的单击事件时。 这是我的孩子(不是最后一个孩子)。

<Button
        onClick={ () => { this.props.randomAdversary }}
        class="fight-button random"
        button="Random adversary"
 />

这里是调用孩子并描述方法的父母:

class Board extends Component {

constructor(props) {
..my constructor
}

randomAdversary() { 
...my function 
}
    return (<div> <FightButton
                            isPlayerTwoPending={this.state.adversaryPending}
                            isPlayerOnePending={this.state.characterPending}
                            isPlayerOneTheWinner={this.state.heroWin}
                            isFighting={this.state.fighting}
                            randomAdversary={this.randomAdversary}
                            fight={this.fight(100)}
                            playAgain={this.playAgain()}
                          />
            </div>
    )
}

当我点击时,我的按钮的类必须改变。但是当我 console.log 类时,它没有改变。我的测试有问题吗?

【问题讨论】:

  • 尝试在shallow(&lt;FightButton.../&gt;);中传递randomAdversary={mockRandomAdv}
  • onClick={ () =&gt; { this.props.randomAdversary }} 应该是onClick={ () =&gt; { this.props.randomAdversary() }}
  • 好的,看来修复很简单,现在触发绑定事件。但现在我必须重构我的代码,使其更具可读性,就像我的孩子的绑定状态一样,而不仅仅是父母的绑定状态,以使其可测试,非常感谢。

标签: javascript reactjs sinon jestjs


【解决方案1】:

查看按钮,我没有看到正确调用函数。我实际上什么也没做,你需要像这样执行函数:

<Button
    onClick={ () => { this.props.randomAdversary() }} // Add the `()`
    class="fight-button random"
    button="Random adversary"
/>

【讨论】:

  • 是的,正如评论中注意到的那样,解决方案似乎触发了调用,谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-06-20
  • 1970-01-01
  • 2023-01-30
  • 2022-12-15
  • 1970-01-01
  • 2016-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多