代码之家  ›  专栏  ›  技术社区  ›  kHRYSTAL

如何检查sinon在Promise中调用的函数

  •  0
  • kHRYSTAL  · 技术社区  · 7 年前

    我在使用 mocha + chai + sinon 测试功能,但承诺使用 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();
        });
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Tristan Hessell    7 年前

    这里的问题是 .catch 块正在捕获 .then

    这是一个问题,因为您正在呼叫 done 未通过 err 对象摩卡将此解释为测试正确通过,而不是失败。


    修复程序:

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