【问题标题】:sinon stub a method that was executed in then call of promisesinon stub 一个在 then 调用 promise 时执行的方法
【发布时间】:2017-07-29 08:47:32
【问题描述】:
describe("/test" , ()=> {

    // separate class 2
    class2 = {

        // function that i wanna stub
    hi: function () {
        return "hi";
    }
    }

// separate class 1
    class1 = {

        // function that i have stubbed and tested
         method1: function() {
           return new Promise((resolve, reject) => {
               resolve(num);

            })
        }

    }

    // method that i will execute
    var parent= function (){

        class1.method1().then(()=>{

            class2.hi();

        })

    }

    // the test
    it("should stub hi method",()=>{


        var hiTest = sinon.stub(class2, 'hi').resolves(5);
        var method1Test = sinon.stub(class1 , 'method1').resolves(5);

     // this start the execution of the promise with then call
        parent();

        // this works fine and test pass
        expect(method1Test.calledOnce.should.be.true);

        // this doesn't work although i executed the function
        expect(hiTest.calledOnce.should.be.true);

    })

})

我想做的是正确测试 hi 方法 ..因为当我测试该方法是否执行一次时

虽然我在 then 调用 promise 时执行了它,但它并没有显示出来,并且它使 calledOnce 测试失败

【问题讨论】:

    标签: unit-testing promise mocha.js sinon chai


    【解决方案1】:

    这里的问题是您正在测试代码,就好像它是同步的,而实际上不是(因为您使用的是Promise)。


    为了能够正确测试这一点,我们需要能够挂钩以 parentcalling class1.method1 开头的承诺链。

    我们可以通过返回调用class1.method1 返回的承诺来做到这一点。

    就测试本身而言,我们需要确保Mocha在等待promise时不会结束测试,所以我们使用done回调参数告诉Mocha我们认为测试是完成了。


    describe("/test", ()=> {
      class2 = {
        hi: function () {
          return "hi";
        }
      }
    
      class1 = {
        method1: function() {
          return new Promise((resolve, reject) => {
            resolve(num);
          })
        }
      }
    
      var parent = function (){
        return class1.method1().then(()=>{
          class2.hi();
        })
      }
    
      it("should stub hi method", (done)=> {
        var hiTest = sinon.stub(class2, 'hi').returns(5);
        var method1Test = sinon.stub(class1 , 'method1').resolves(5);
    
        parent().then(() => {
          expect(method1Test.calledOnce.should.be.true);
          expect(hiTest.calledOnce.should.be.true);
          done();
        });
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 2018-08-28
      • 2018-12-28
      • 2017-02-21
      • 2016-05-13
      相关资源
      最近更新 更多