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

JS UnitTesting Mocha中的方法链

  •  1
  • dennismonsewicz  · 技术社区  · 11 年前

    我有这样一个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 回复  |  直到 11 年前
        1
  •  3
  •   robertklep    11 年前

    下面是一个独立的演示:

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

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

    如果要允许链接,方法存根需要返回 克尼克斯 树桩:

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