JS 单元测试 Mocha 中的方法链

JS UnitTesting a method chain in Mocha

我有一个像这样的 ES6 方法:

/**
* Builds a knex object with offset and limit
* @param {Object} pagination
* @param {number} pagination.count - limit query to
* @param {number} pagination.start - start query at
* @returns {QueryBuilder}
*/
buildPagination (pagination) {
    if (_.isEmpty(pagination)) {
        return this;
    }

    let count = pagination.count;
    let start = pagination.start;

    this.knex = this.knex.offset(start);

    if (count !== undefined) {
        this.knex = this.knex.limit(count);
    }

    return this;
}

我的测试如下:

describe("#buildPagination", () => {
    let knex;
    let b;
    let pagination;

    beforeEach(() => {
        knex = sinon.stub();
        knex.offset = sinon.stub();
        knex.limit = sinon.stub();
        b = new QueryBuilder(knex);
        pagination = {
            start: 3,
            count: 25
        };
    });

    it.only("should attach limit and offset to knex object", () => {
        let res = b.buildPagination(pagination).knex;

        console.log(res);

        assert(res.offset.calledOnce);
        assert(res.offset.calledWith(3));
        assert(res.limit.calledAfter(res.offset))
        // assert(res.knex.limit.calledWith(25));
    });
});

我 运行 的错误是 TypeError: Cannot read property 'limit' of undefined。此行发生错误:this.knex = this.knex.limit(count);

这是一个独立的演示:

var knex    = sinon.stub();  
knex.limit  = sinon.stub();
knex.offset = sinon.stub();

knex = knex.offset();

在这一点上,knexundefined 因为你的存根实际上 return 什么都没有。当您随后调用 knex.limit() 时,您会得到 TypeError.

如果您想允许链接,您的方法存根需要 return knex 存根:

knex.limit  = sinon.stub().returns(knex);
knex.offset = sinon.stub().returns(knex);