Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test value of variable inside javascript function - sinon / chai

I've got the following function in a React component:

parentFunction: function(items){
  let variableOfInterest = this.callThisFunction().toArray().filter((ele) => {
    if(obj[ele.get('id')]){
      return ele
    }
  }).map((ele) => ele.get('id'))

  this.setState({newState:variableOfInterest})
}

I'm able to write a test for the invocation of callThisFunction using stubs, but have been unable to figure out if it is possible use sinon or chai to spy on the value of the variableOfInterest. I'd like to write a test where I can pass in an argument, and use 'expect' to test for the result's value. It doesn't really make sense to return the value either at the end - and doing so just for the test seems unnecessary. I'd also love to be able to test for the result of calling toArray(), and also filter() if that is possible. Thanks for any insight!

This is my test for the invocation of callThisFunction():

it('should call callThisFunction() once', () => {   
  let callThisFunctionStub = sinon.stub(prototype, 'callThisFunction')
  let stub = callThisFunctionStub.callsFake(() => objectToReturn)
  prototype.callParentFunction(items)
  sinon.assert.calledOnce(stub)
})
like image 466
zero_cool Avatar asked Oct 18 '22 06:10

zero_cool


1 Answers

I'd like to write a test where I can pass in an argument, and use 'expect' to test for the result's value.

Option 1:

You can simply use the state to get the updated value of newState, and compare it to your expected value.

This can be done very easily by using the airbnb/enzyme library to test your React component. Enzyme also uses mocha and chai, so the syntax will be almost identical. It also provides a spy and mock API, if you want to use them -- although you probably wouldn't need to in this case.

Here is an example of the API to get .state() via shallow rendering:

const wrapper = shallow(<MyComponent />);
expect(wrapper.state().foo).to.equal(10);
expect(wrapper.state('foo')).to.equal(10);

So you would need to write test for the Component which has the parentFunction, do a shallow mount of that Component, simulate the call of parentFunction, then get state and check its value.

Option 2:

If you don't want to check the state, or want to write more involved tests for the computation of variableOfInterest, you can try moving the computation code into a different function, and write tests for that function.

like image 93
ryder Avatar answered Oct 21 '22 07:10

ryder