JS UnitTesting Mocha中的方法链

时间:2015-08-06 17:36:44

标签: javascript 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);

1 个答案:

答案 0 :(得分:3)

这是一个独立的演示:

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

knex = knex.offset();

此时,knexundefined,因为您的存根实际上并未返回任何内容。当您随后致电knex.limit()时,您会收到TypeError

如果要允许链接,则方法存根需要返回knex存根:

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