Search code examples
node.jssinonstub

Sinon stub on prototype, check value of actual instance it is called on


I have a sinon stub on a prototype and method...

stub = sinon.stub(MyType.prototype, 'someFunction');

MyType has some value in a property depending on which instance it is. Lets call the property identifier.

I need to check two things...

  1. That someFunction was called with the correct parameters. expect(stub).to.have.been.calledWith('Some Parameter'); (This works as expected).

  2. That the identifier of the instance the function was called on is correct. There are many instances of MyType and I need to check the function was called on the correct one.

I can do the first check. But I don't know how to (or even if) I can do the second check.

Is this possible?

Thanks


Solution

  • Yes, this is possible.

    You can use sinon.assert.calledOn, spy.calledOn, spyCall.thisValue, or spy.thisValues to check the this value for calls:

    import * as sinon from 'sinon';
    
    class MyType {
      constructor(id) {
        this.identifier = id;
      }
      someFunction(arg) { }
    }
    
    test('someFunction', () => {
      const stub = sinon.stub(MyType.prototype, 'someFunction');
    
      const one = new MyType("oneId");
      const two = new MyType("twoId");
    
      one.someFunction('firstArg');
      two.someFunction('secondArg');
    
      sinon.assert.calledWith(stub.firstCall, 'firstArg');  // SUCCESS
      sinon.assert.calledOn(stub.firstCall, one);  // SUCCESS
      expect(stub.firstCall.thisValue.identifier).to.equal('oneId');  // SUCCESS
    
      sinon.assert.calledWith(stub.secondCall, 'secondArg');  // SUCCESS
      sinon.assert.calledOn(stub.secondCall, two);  // SUCCESS
      expect(stub.secondCall.thisValue.identifier).to.equal('twoId');  // SUCCESS
    });