rivets-backbone-is-required.spec.js 2.69 KB
define(function(require) {
    'use strict';

    var $ = require('jquery');
    window.jQuery = $;
    var RivetsBackboneIsRequired = require('rivets-backbone-is-required');
    var _ = require('underscore');
    var Backbone = require('backbone');
    var rivets = require('rivets');
    require('backbone-validation');
    require('rivets-backbone-adapter');
    _.extend(Backbone.Model.prototype, Backbone.Validation.mixin);
    //rivets.config.rootInterface = ':';

    describe('RivetsBackboneIsRequired', function() {
        it('returns undefined', function() {
            expect(RivetsBackboneIsRequired).toBeUndefined();
        });
        var Person, Address;
        beforeEach(function() {
            Person = Backbone.Model.extend({
                defaults: {
                    firstName: '',
                    middleName: '',
                    lastName: '',
                },
                validation: {
                    firstName: [
                        {required: true},
                    ],
                    lastName: {
                        required: function() { return true; },
                    },
                },
            });
            Address = Backbone.Model.extend({
                defaults: {
                    address1: '',
                },
            });
        });
        var person, address, model;
        beforeEach(function() {
            person = new Person({
                firstName: 'Adam',
                lastName: 'Heath',
            });
            address = new Address();
            model = new Backbone.Model({person: person, address: address});
        });
        function buildTest(objName, fieldName, wantedValue, isRequired) {
            it(objName + ':' + fieldName + '=' + isRequired, function() {
                var span = document.createElement('span');
                span.setAttribute('rv-text', ':' + objName + ':' + fieldName);
                span.setAttribute('rv-class-required', ':' + objName + ' | is-required \'' + fieldName + '\'');
                //console.log('before bind', span.outerHTML);
                var view = rivets.bind(span, model);
                //console.log('after bind', span.outerHTML);
                if (isRequired) {
                    expect(span.getAttribute('class')).toMatch(/\brequired\b/);
                } else {
                    expect(span.getAttribute('class')).toBe(null);
                }
            });
        }
        buildTest('person', 'firstName', 'Adam', true);
        buildTest('person', 'middleName', '', false);
        buildTest('person', 'lastName', 'Heath', true);
        buildTest('address', 'address1', '', false);
        buildTest('missing', 'field', '', false);
    });
});