This is the child article of ReactTestUtils - Tutorial. In this article, I will explain how to Verify Function Calls with examples.

Example

Here we pass clickFunc and dblClickFunc as properties, now we have to check whether these functions were called or not.
import React from 'react';

class FuncComponent  extends React.Component {

    constructor(props) {
        super(props);
        this.dblClickEventFunc = this.dblClickEventFunc.bind(this);
    }

    dblClickEventFunc() {
        this.props.dblClickFunc('this is some sample arg value');
    }

    render () {
   return <div>
      <div id="clickEventDiv" onClick={this.props.clickFunc}>
      </div>
      <div id="dblClickEventDiv" onDoubleClick={this.dblClickEventFunc}>
      </div>
    </div>;
    }

}

FuncComponent.propTypes = {
  clickFunc:React.PropTypes.func,
  dblClickFunc:React.PropTypes.func
}

FuncComponent.defaultProps = {

}

export default FuncComponent;

Verify Function Call

Here done callback has to be called at end of the test.  Whenever you simulate the click event, clickFunction will be called. clickFunction will call done callback function, so the test will end with success message 
it('function call on click test', (done) => {
    let clickFunction = () => {
      done();
    };
    let instance = ReactTestUtils.renderIntoDocument(
      <FuncComponent clickFunc={clickFunction}/>
    );
    let clickDiv = scryRenderedDOMComponentsWithId(instance, "clickEventDiv");
    ReactTestUtils.Simulate.click(clickDiv[0]);
});

Verify Function Argument

Whenever you simulate double click event,  dblClickFunction will be called with argument. Here we are checking that argument value in dblClickFunction, then calling done callback function.
it('function argument verification on double click test', (done) => {
    let dblClickFunction = (arg) => {
      expect(arg).toEqual('this is some sample arg value');
      done();
    };
    let instance = ReactTestUtils.renderIntoDocument(
      <FuncComponent dblClickFunc={dblClickFunction}/>
    );
    let clickDiv = scryRenderedDOMComponentsWithId(instance, "dblClickEventDiv");
    ReactTestUtils.Simulate.doubleClick(clickDiv[0]);
});

2 comments:

  1. This was an terrific post. Thanks for providing these details.
    buy logo design

    ReplyDelete
  2. HEY!
    It's very amazing post, thanks for sharing it with us.


    law dissertation Writers

    ReplyDelete

Blogroll

Popular Posts