茉莉花单元测试中未调用存根

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");
        });

收到 Dstub 已被调用 0 次的错误。谁能帮我解决这个问题?

如果不进一步了解您的代码,很难判断,但看起来这一行并没有像您认为的那样存根:

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

这似乎是在 A.B.C() 一个 调用上存根 D 函数,而不是另一个。换句话说,fun 中的 A.B.C() 与您的 beforeEach 中的 A.B.C() 不同,因此您输入的内容不正确。

如果您可以存根任何 A.B.C() return 的 原型 ,那可能会解决您的问题。

您还可以将 A.B.C() 的结果存根到 return 您想要的 Dstub:

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
    });
  });

  // ...

希望对您有所帮助!