unit testing - Test value of variable inside javascript function - sinon / chai -


i've got following function in 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 write test invocation of callthisfunction using stubs, have been unable figure out if possible use sinon or chai spy on value of variableofinterest. i'd write test can pass in argument, , use 'expect' test result's value. doesn't make sense return value either @ end - , doing test seems unnecessary. i'd love able test result of calling toarray(), , filter() if possible. insight!

this test 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) }) 

i'd write test can pass in argument, , use 'expect' test result's value.

option 1:

you can use state updated value of newstate, , compare expected value.

this can done using airbnb/enzyme library test react component. enzyme uses mocha , chai, syntax identical. provides spy , mock api, if want use them -- although wouldn't need in case.

here example of api .state() via shallow rendering:

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

so need write test component has parentfunction, shallow mount of component, simulate call of parentfunction, state , check value.

option 2:

if don't want check state, or want write more involved tests computation of variableofinterest, can try moving computation code different function, , write tests that function.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -