I have a react component which has a method

export class Hit extends React.Component {
    constructor(props) {
        super(props);
        this.triggerClick= this.triggerClick.bind(this);
    }

triggerClick(event) {
    this.props.triggerClick(event.target.click);
}

render() {
    return (
....................................
                        <input ........ onChange={this.triggerClick} />
.............................................
           );
    }
}

I want to check if triggerClick(event) method is being called or not. Hence, I am pasting the code I have related to this. Though if you see in the logs of the hitComponent something like below,

onChange: [Function: bound triggerClick]

log of spy says it is not being called. Not sure where I am going wrong.

let mockFunction = sinon.fake();

let hitComponent = renderShallow(<Hit ........ triggerClick= {mockFunction}/>)

let spy = sinon.spy(Hit.prototype, 'triggerClick');

console.log(hitComponent)
console.log(spy)

o/p: hitComponent:

[ { '$$typeof': Symbol(react.element),
    type: 'input',
    key: null,
    ref: null,
    props:
     { type: '.....',
       checked: true,
       onChange: [Function: bound triggerClick] },
.....}]

o/p: spy:

{ [Function: proxy]
  isSinonProxy: true,
  called: false,
  notCalled: true,
  calledOnce: false,
  calledTwice: false,
  calledThrice: false,
  callCount: 0,
  firstCall: null,
  secondCall: null,
  thirdCall: null,
  lastCall: null,
  args: [],
  returnValues: [],
  thisValues: [],
  exceptions: [],
  callIds: [],
  errorsWithCallStack: [],
  displayName: 'triggerClick',
  toString: [Function: toString],
  instantiateFake: [Function: create],
  id: 'spy#1',
  stackTraceError:
   Error: Stack Trace for original
       at wrapMethod ..........

 restore: { [Function] sinon: true },
  wrappedMethod: [Function: triggerClick]
}

There is a helper class to use react-test-renderer

import ShallowRenderer from 'react-test-renderer/shallow';


function renderShallow(component) {
    const shallowRenderer = new ShallowRenderer();
    shallowRenderer.render(component);
    return  shallowRenderer.getRenderOutput();;
}

export {renderShallow}
1

There are 1 best solutions below

6
On

triggerClick is bound when a class is instantiated. It cannot be spied or mocked on Hit.prototype after that.

It should be either:

let spy = sinon.spy(Hit.prototype, 'triggerClick');
let hitComponent = renderShallow(<Hit triggerClick= {mockFunction}/>)

Or:

let hitComponent = renderShallow(<Hit triggerClick= {mockFunction}/>)
sinon.spy(hitComponent.instance(), 'triggerClick');