【问题标题】:Test if function is called react and enzyme测试函数是否称为反应和酶
【发布时间】:2017-03-16 13:33:06
【问题描述】:

我正在尝试测试我的反应组件中的一种方法。单击按钮后会调用它,因此我可以使用酶进行模拟

 it('clone should call handleCloneClick when clicked', () => {
        const cloneButton = wrapper.find('#clone-btn');
        cloneButton.simulate('click');
 });

我的组件方法在这里:

_handleCloneClick(event) {
    event.preventDefault();
    event.stopPropagation();

    this.props.handleClone(this.props.user.id);
}

当用户单击模拟中的按钮时正在调用 _handleCloneClick,我该如何测试它是否已成功调用?

【问题讨论】:

    标签: reactjs sinon enzyme


    【解决方案1】:

    有两种选择,在渲染组件之前,你应该监视组件原型的_handleCloneClick

    export default class cloneButton extends Component {
      constructor(...args) {
        super(...args);
        this. _handleCloneClick = this. _handleCloneClick.bind(this);
      }
    
      _handleCloneClick() {
        event.preventDefault();
        event.stopPropagation();
    
        this.props.handleClone(this.props.user.id);
      }
    
      render() {
        return (<button onClick={this. _handleCloneClick}>Clone</button>);
      }
    }
    

    在你的测试中:

    it('clone should call handleCloneClick when clicked', () => {
      sinon.spy(cloneButton.prototype, '_handleCloneClick');
      const wrapper = mount(<cloneButton/>);
      wrapper.find('#clone-btn').simulate('click');
      expect(spy).toHaveBeenCalled() //adept assertion to the tool you use
    });
    

    或者,您可以尝试在渲染组件后设置一个间谍,然后调用wrapper.update()

    it('clone should call handleCloneClick when clicked', () => {      
      const wrapper = mount(<cloneButton/>);
      sinon.spy(wrapper.instance(), "_handleCloneClick");
      wrapper.update();
      wrapper.find('#clone-btn').simulate('click');
      expect(spy).toHaveBeenCalled() //adept assertion to the tool you use
    });
    

    【讨论】:

    • 你应该知道,如果你在原型中添加一个间谍,它也会改变每个后续测试的行为。
    • 严格来说你不应该测试私有方法。你应该监视 handleClone 属性来测试预期的行为。
    • 当我尝试此“expect(jest.fn())[.not].toHaveBeenCalled() jest.fn() 值必须是模拟函数或间谍时收到以下错误。收到:函数:[函数代理]"
    • @Jonathan 您可以使用sinon.createSandbox 创建一个沙盒,并在每次测试后调用sandbox.restore()
    猜你喜欢
    • 2019-01-30
    • 2017-09-24
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 2020-08-22
    • 2017-06-26
    • 2020-06-01
    • 1970-01-01
    相关资源
    最近更新 更多