【问题标题】:How to checking function called in Promise by sinon如何检查sinon在Promise中调用的函数
【发布时间】:2018-01-08 08:47:57
【问题描述】:

我用mocha+chai+sinon来测试函数,但是在promise中使用called属性,即使写了一个未定义的函数,called总是true,这是什么原因造成的?以及如何解决?thx

describe("when click get verifycode", function () {
it('if get server response success, should start countdown', function (done) {
    // given
    sandbox.stub(model, 'getVerifyCode').resolves({});
    sandbox.spy(view, 'startCountDown');
    // when
    var result = instance.onClickVerify('123456');
    // then
    result.then(res => {
        // no matter what function, called always true
        // e.g. expect(AnUndefinedFunction.called).to.be.ok;
        expect(instance.view.startCountDown.called).to.be.ok;
        done();
    }).catch(err => {
        done();
    });

【问题讨论】:

    标签: javascript testing mocha.js sinon


    【解决方案1】:

    这里的问题是.catch 块正在捕获.then 块中发生的任何错误。

    这是一个问题,因为您在调用 done 时没有传递 err 对象。 Mocha 将此解释为测试正确通过,而不是失败。


    修复:

    describe("when click get verifycode", function () {
        it('if get server response success, should start countdown', function (done) {
            // given
            sandbox.stub(model, 'getVerifyCode').resolves({});
            sandbox.spy(view, 'startCountDown');
            // when
            var result = instance.onClickVerify('123456');
            // then
            result.then(res => {
                // no matter what function, called always true
                // e.g. expect(AnUndefinedFunction.called).to.be.ok;
                expect(instance.view.startCountDown.called).to.be.ok;
                done();
            }).catch(err => {
                done(err);
            });
        })
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 2017-02-12
      • 2015-06-30
      • 2019-05-14
      • 1970-01-01
      相关资源
      最近更新 更多