Backbone集合使用mocha初始化函数测试

时间:2015-02-03 17:19:06

标签: backbone.js mocha sinon chai

我如何为options.url的{​​{1}}函数的initilaize参数编写测试?

我有以下代码,但在编写测试时遇到问题。我使用的是Backbone.CollectionMochaChai。当我在我的Backbone Collection中注释掉Sinonjs时测试通过了,但是当我取消注释时,我得到以下断言错误:

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); }); }); }); 代码段?

1 个答案:

答案 0 :(得分:0)

事实证明它就像在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");
        });