繁体   English   中英

React:测试作为道具传递并由父级触发的功能

[英]React : test a function which is passed as a props and is triggered by the parent

我正在尝试触发测试的点击事件。 因此:

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()的click事件返回未定义。 这是我的孩子(不是最后一个孩子)。

<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类中使用时,它也没有改变。 我的考试有问题吗?

看着按钮,我看不到正确调用该函数。 我实际上什么也没做,您需要执行以下功能:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM