【问题标题】:How can I fix this Q.denodify test?如何修复此 Q.denodify 测试?
【发布时间】:2023-03-21 20:55:01
【问题描述】:

我正在使用一个数据库库,其基于回调的接口如下所示:

var DB = {
    insert: function(options, callback) {

    }
}

我想围绕这个数据库实现一个包装器,以将其回调样式 API 转换为基于 Promise 的 API。为此,我定义了以下类:

var DatabaseWrapper = {
    init: function(db) {
        this.db = db;
    },
    insert: function(options) {
        return Q.denodeify(this.db.insert.bind(this.db))(options);
    }
}

我想编写一个单元测试来确保当我调用DatabaseWrapper.insert 时它调用DB.insert。到目前为止,我的测试如下所示:

describe('DatabaseWrapper', function () {
    var wrapper, insertSpy, bindStub;

    beforeEach(function () {
        wrapper = Object.create(DatabaseWrapper);
        insertSpy = sinon.spy(function () {
            console.log('insertSpy got called');
        });
        bindStub = sinon.stub();

        wrapper.db = {
            insert: function (options, callback) {
            }
        };

        sinon.stub(wrapper.db.insert, 'bind').returns(insertSpy);
    });


    describe('#insert', function () {
        it('should delegate to db.insert', function (done) {
            wrapper.insert({herp: 'derp'});

            expect(wrapper.db.insert.bind).to.have.been.calledOnce;

            // This fails but I expect it to succeed
            expect(promise).to.have.been.calledOnce;
        })
    });
});

数据库实例的插入方法实际上在测试失败后被调用,因为'insertSpy got called' 消息打印在控制台中。

但显然它在测试失败后被调用。

据我所知,这是由于 Node 的 process.nextTick 的工作方式。所以对回调的调用发生在测试失败之后。有没有办法在不依赖第三方库的情况下修复这个测试(例如q-flush)?

【问题讨论】:

  • 这是一个异步测试 - 使用异步 promise 语法。
  • @Benjamin 您能否提供解决方案作为答案?
  • 您在使用 Mocha 进行测试吗?
  • 是的,我正在使用 Mocha。
  • 好的,请将 mocha 标签添加到您的问题中,我会添加答案。

标签: javascript node.js promise q sinon


【解决方案1】:

您正在执行异步操作,因此最好执行异步测试。添加setTimeout 仍然会使您容易出现竞争条件。

describe('#insert', function () {
        it('should delegate to db.insert', function () { // no done here
            // note the return here to signal to mocha this is a promise test 
            return wrapper.insert({herp: 'derp'}).then(function(){
              // add expects here, rest of asserts should happen here
              expect(wrapper.db.insert.bind).to.have.been.calledOnce;   
            }); 
        })
    });
});

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2010-12-22
    • 2011-12-30
    • 2021-01-29
    相关资源
    最近更新 更多