Search code examples
javascriptnode.jsunit-testingsinonpartial-application

spy on all args passed to a function composition


I'm trying to spy on all the params passed to a side-effect-ey function, which is composed with an anonymous function container receiving a final param

(actually i want to stub it, but spying would be a start)

classA.js

const classB = require(`classB.js`)

const doWork = ( a, b, c, d, e ) => {
  //do things with a, b, c, d, e to make x, y, z…
  return classB.thingToSpyOn(a, b, c, x, y)(z) //<=note curry here
}

ClassA.spec.js

const classA = require(`classA.js`)
const classB = require(`classB.js`)

describe(`doWork`, () => {
  sinon.spy(classB, 'thingToSpyOn' ) 

  classA.doWork( “foo”, “bar”, “baz”, “bing”, “boing”)

  //now i can get the spy to tell me what it received as a, b, c, x, y
  console.log(classB.thingToSpyOn.args)
  ...

but how to log what was received as z?


Solution

  • A stub is actually required for this:

    describe(`doWork`, () => {
      let zSpy = sinon.spy();
      sinon.stub(classB, 'thingToSpyOn' ).returns(zSpy);
    
      classA.doWork( 'foo', 'bar', 'baz', 'bing', 'boing' )
    
      console.log(classB.thingToSpyOn.args)
      console.log(zSpy.args)
    })
    

    This doesn't call through to the curried function, but that's not required if you only want to check the argument that gets passed.