【问题标题】:Backbone collection initialize function test with mocha使用 mocha 进行骨干收集初始化功能测试
【发布时间】:2015-04-03 00:04:50
【问题描述】:

我将如何为Backbone.Collection 的initilaize 函数的options.url 参数编写测试?

我有以下代码,但无法为其编写测试。我正在使用Mocha、Chai 和Sinonjs。当我在我的 Backbone 集合中注释掉 this.url = options.url 时,测试通过了,但是当我取消注释它时,我得到以下断言错误:

TypeError: 'undefined' is not an object (evaluating 'options.url')

我的主干代码:

Foo.Collection._entity = Backbone.Collection.extend({
    url: '',        //API's endpoint for this collection
    fetched: false, //flag to avoid fetching twice if consecutive fetches occur

    /**
     * Makes sure the URL is set
     * @param {Object[]} models Set of initial models
     * @param {Object} options Regular initialization options object
     */
    initialize: function (models, options) {
        models = models || [];
        this.url = options.url;
    }
});

我对这个集合的测试

describe("Foo.Collection._entity", function () {

    beforeEach(function () {
        // Sinon fake server for the backend
        this.server = sinon.fakeServer.create();

        // Server automatically responds to XHR requests

        this.server.autoRespond = true;

        this.entity = new Foo.Collection._entity();

    });

    afterEach(function () {
        // stop fake server
        this.server.restore();
    });

    describe("Default values", function () {

        // test default values
        it("has default values", function () {
            expect(this.entity).to.be.ok;
            expect(this.entity).to.have.length(0);
        });

        it("default url to be ' '",function() {
            var entity = this.entity;
            expect(entity.url).to.be.equal("");
        });

        it("fetched flag to be set to false", function (){
            var entity = this.entity;
            expect(entity.fetched).to.be.equal(false);
        });
    });
});

我将如何编写测试以通过this.url = options.url sn-p?

【问题讨论】:

    标签: backbone.js mocha.js sinon chai


    【解决方案1】:

    事实证明,这很简单,例如,只需在 beforeEach 函数中使用正确的参数实例化 Collection,然后测试 url 和 Collection 的长度。

     this.entity = new Foo.Collection._entity({options:
                {
                    url: "/Foo"
                }
            });
    
       describe("Default values", function () {
    
            // test default values
            it("has default values", function () {
                expect(this.entity).to.be.ok;
                expect(this.entity).to.have.length(1);
                expect(entity.url).to.be.equal("Foo");
            });
    

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 2015-04-29
      • 2012-10-28
      • 2021-01-23
      • 2021-07-01
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多