Search code examples
jasminejasmine-jqueryjasmine-node

Stub not getting called in jasmine unit test


 function fun{
    A.B.C().D(someconstant);
    $(element).prop("checked",false).trigger("change");
    }

    describe(()=>{
        let triggerStub: Sinon.SinonStub; 
        let Dstub: Sinon.SinonStub;
        beforeEach(() => {
        triggerStub = sandboxInstance.stub($.fn, "trigger");
        Dstub = sandboxInstance.stub(A.B.C(),"D");
        });
        it("Verification",()=>{
        fun();
        sinon.assert.calledOnce(Dstub);
        sinon.assert.calledWithExactly(triggerStub,"change");
        });

Getting an error that Dstub has been called 0 times. Can anyone help me out with this?


Solution

  • It's hard to tell without knowing more about your code, but it looks like this line isn't stubbing what you think it's stubbing:

    Dstub = sandboxInstance.stub(A.B.C(),"D");
    

    This seems to be stubbing the D function on one call of A.B.C(), but not the other. In other words, the A.B.C() in fun is not the same A.B.C() as in your beforeEach, so you're not stubbing the correct thing.

    If you can stub the prototype of whatever A.B.C() returns, that might solve your problem.

    You can also stub the result of A.B.C() to return the Dstub you want:

    describe(() => {
      let triggerStub: Sinon.SinonStub; 
      let Dstub: Sinon.SinonStub;
    
      beforeEach(() => {
        triggerStub = sandboxInstance.stub($.fn, "trigger");
    
        // Create the stub for D.
        DStub = sandboxInstance.stub();
    
        // Make A.B.C() return that stub.
        sandboxInstance.stub(A.B, 'C').returns({
          D: Dstub
        });
      });
    
      // ...
    

    Hope that helps!