测试骨干模型从具有mocha的另一个模型扩展

时间:2015-02-05 10:53:56

标签: testing backbone.js model mocha

当我运行我的测试(我使用Mocha, Chai and Sinon)从另一个骨干模型扩展的骨干模型时,我收到一个错误:

TypeError: 'undefined' is not an object (evaluating 'Model._entity')

我认为通过实例化Model._entity这个错误会消失,但事实并非如此。我应该使用存根吗?

我在网上搜索了答案,但所有示例都是针对直接从Backbone而非其他模型扩展的模型。

我需要做些什么才能避免此错误?

我的测试代码:

describe("Model.address", function () {

    beforeEach(function () {

        // build up a fake server
        this.server = sinon.fakeServer.create();

        this.server.autoRespond = true;

        this.parentModel = new Model._entity();

        this.Model_address = new Model.Address();
    });


    afterEach(function () {

        // delete fake server
        this.server.restore();
    });

    describe("Defaults", function () {

        // test defaults
        it("has default values", function () {
            // create empty model
            var model = this.Model_address;

            // expect model to be truthy
            expect(model).to.be.ok;


        });

    });
});

Model._entity:

Model._entity = Backbone.Model.extend({

    initialize: function(options) {

        //If options passed with created and/or modified values, set the corresponding model attributes
        if (options && options.created && typeof options.created === 'string') {
            this.set('created', new Date(options.created));
        }
        if (options && options.modified && typeof options.modified === 'string') {
            this.set('modified', new Date(options.modified));
        }
    },

    defaults: function() {
        return {
            created: new Date(),
            modified: new Date()
        };
    }
});

Model.Address:

Model.Address = Model._entity.extend({
    invalidField: false,

    defaults: function () {
        var superDefs;  //defaults 'inherited' from parent model  

        superDefs = Model._entity.prototype.defaults.apply(this, arguments);
        return _.defaults(superDefs, {
            firstLine: '',
            secondLine: '',
            postalCode: '',     //TODO: move down
            houseNumber: '',    //TODO: move up 
            city: '',
            country: 'uk'
        });
    },

    urlRoot: function () {
        return '/checkout/address';
    },

    validate: function (attributes, options) {
        var attr;

        for (attr in attributes) {
            if (attributes[attr] === '') {
                this.invalidField = true;
                return 'Blank field';
            }
        }
    }
});

0 个答案:

没有答案