<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
    testVerifyWaysToAccessAttributes: {
        test: function(component){
            /**
             * There are 3 ways to access Attribute values on a Component.
             * This test verifies that all 3 ways get the same result.
             */
            var stringValueThroughComponentApi = component.getValue('{!v.label}');
            aura.test.assertNotNull(stringValueThroughComponentApi,"Cound not retrieve attribute using getAttributes().getValue()");

            var stringValueByExpression = $A.expressionService.getValue(component, "{!v.label}");
            aura.test.assertNotNull(stringValueByExpression,"Cound not retrieve attribute using expression service");

            var attributeSet = component.getAttributes();
            aura.test.assertTrue(attributeSet.values.auraType ==='Value', 'aura type for attribute set is not set');

            var attribute = component.getAttributes().getValue('label');
            aura.test.assertNotNull(attribute,"Cound not retrieve component's attribute");
            //Attributes are value objects but the auraType is changed to Attribute. see
            aura.test.assertTrue(attribute.auraType ==='Value', 'aura type for attribute not set');
            var stringValueThruComponent = attribute.getValue();

            //Verify that all of them returned the same value
            aura.test.assertEquals(stringValueThruComponent,stringValueThroughComponentApi.getValue(),'Attribute values differ across various access types');
            aura.test.assertEquals(stringValueThruComponent,stringValueByExpression.getValue(),'Attribute values differ across various access types');
        }

    },
    testVerifyWaysToModifyAttributes: {
        test: function(component){
            /**
             * There are 3 ways to set values on a Component's Attribute.
             * This test verifies that all 3 ways can change the values.
             */
            component.setValue('{!v.label}' , 'newLabel');
            var labelValueThroughComponentApi = component.getValue('{!v.label}').getValue();
            var labelValueByExpression = $A.expressionService.getValue(component, "{!v.label}").getValue();
            var labelValueThruComponent = component.getAttributes().getValue('label').getValue();

            //Verify that all of them see the same value
            aura.test.assertEquals(labelValueThruComponent,'newLabel');
            aura.test.assertEquals(labelValueThruComponent,labelValueThroughComponentApi);
            aura.test.assertEquals(labelValueThruComponent,labelValueByExpression);

            $A.expressionService.setValue(component, "{!v.label}" , 'AttributeDefault');
            var labelValueThroughComponentApi = component.getValue('{!v.label}').getValue();
            var labelValueByExpression = $A.expressionService.getValue(component, "{!v.label}").getValue();
            var labelValueThruComponent = component.getAttributes().getValue('label').getValue();

            //Verify that all of them see the same value
            aura.test.assertEquals(labelValueThruComponent,'AttributeDefault');
            aura.test.assertEquals(labelValueThruComponent,labelValueThroughComponentApi);
            aura.test.assertEquals(labelValueThruComponent,labelValueByExpression);

            component.getAttributes().setValue('label','newLabel');
            var labelValueThroughComponentApi = component.getValue('{!v.label}').getValue();
            var labelValueByExpression = $A.expressionService.getValue(component, "{!v.label}").getValue();
            var labelValueThruComponent = component.getAttributes().getValue('label').getValue();

            //Verify that all of them see the same value
            aura.test.assertEquals(labelValueThruComponent,'newLabel');
            aura.test.assertEquals(labelValueThruComponent,labelValueThroughComponentApi);
            aura.test.assertEquals(labelValueThruComponent,labelValueByExpression);
        }

    },
    testVerifyCommitFunctionOnAttributes: {
        test: function(component){
            /**Attributes of a Component are stored as value objects
             * Verify that such value objects can be committed
             */
            var stringValue = component.getAttributes().getValue('label');
            aura.test.assertTrue(stringValue.getValue()==="AttributeDefault", "Value mis match between attribute value and retrieved value");
            stringValue.setValue('newString');

            aura.test.assertTrue(stringValue.getValue()==='newString', "getValue is not retrieving the latest value");
            aura.test.assertTrue(component.getAttributes().getValue('label').getPreviousValue()==='AttributeDefault', "getPreviousValue is not retrieving the previous value");
            //Commit a value
            component.getAttributes().getValue('label').commit();
            aura.test.assertTrue(component.getAttributes().getValue('label').getPreviousValue()==="newString", "Value was not committed");
        }

    },
    testVerifyInsertingNewAttributes:{
        test: function(component){
            //Calling getValue() on a non existing key (attribute)
            var attributeSet = component.getAttributes();
            var newValue = attributeSet.getValue('nonExistingAttribute');
            aura.test.assertFalse(newValue.isDefined(), 'A defined Value object was created');
            //TODO: W-795118
            //aura.test.assertTrue(attributeSet.getValue('nonExistingAttribute').getValue()==='blah', "New member value not editable");
        }
    },

    testInvalidUseOfGetAttributes:{
        test: function(component){
            var attributeSet = component.getAttributes();
            var attrValue = attributeSet.getValue('label');
            //attrValue.getValue() is the actual usage of a wrapped value object
            var newBlankValue = attrValue.getValue('blah');
            aura.test.assertDefined(newBlankValue, 'A Value was not created');
        }
    }

})
<commit_msg>Merging origin/tbliss/master-pending-attributeSet-nonexistent into master<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
    testVerifyWaysToAccessAttributes: {
        test: function(component){
            /**
             * There are 3 ways to access Attribute values on a Component.
             * This test verifies that all 3 ways get the same result.
             */
            var stringValueThroughComponentApi = component.getValue('{!v.label}');
            aura.test.assertNotNull(stringValueThroughComponentApi,"Cound not retrieve attribute using getAttributes().getValue()");

            var stringValueByExpression = $A.expressionService.getValue(component, "{!v.label}");
            aura.test.assertNotNull(stringValueByExpression,"Cound not retrieve attribute using expression service");

            var attributeSet = component.getAttributes();
            aura.test.assertTrue(attributeSet.values.auraType ==='Value', 'aura type for attribute set is not set');

            var attribute = component.getAttributes().getValue('label');
            aura.test.assertNotNull(attribute,"Cound not retrieve component's attribute");
            //Attributes are value objects but the auraType is changed to Attribute. see
            aura.test.assertTrue(attribute.auraType ==='Value', 'aura type for attribute not set');
            var stringValueThruComponent = attribute.getValue();

            //Verify that all of them returned the same value
            aura.test.assertEquals(stringValueThruComponent,stringValueThroughComponentApi.getValue(),'Attribute values differ across various access types');
            aura.test.assertEquals(stringValueThruComponent,stringValueByExpression.getValue(),'Attribute values differ across various access types');
        }

    },
    testVerifyWaysToModifyAttributes: {
        test: function(component){
            /**
             * There are 3 ways to set values on a Component's Attribute.
             * This test verifies that all 3 ways can change the values.
             */
            component.setValue('{!v.label}' , 'newLabel');
            var labelValueThroughComponentApi = component.getValue('{!v.label}').getValue();
            var labelValueByExpression = $A.expressionService.getValue(component, "{!v.label}").getValue();
            var labelValueThruComponent = component.getAttributes().getValue('label').getValue();

            //Verify that all of them see the same value
            aura.test.assertEquals(labelValueThruComponent,'newLabel');
            aura.test.assertEquals(labelValueThruComponent,labelValueThroughComponentApi);
            aura.test.assertEquals(labelValueThruComponent,labelValueByExpression);

            $A.expressionService.setValue(component, "{!v.label}" , 'AttributeDefault');
            var labelValueThroughComponentApi = component.getValue('{!v.label}').getValue();
            var labelValueByExpression = $A.expressionService.getValue(component, "{!v.label}").getValue();
            var labelValueThruComponent = component.getAttributes().getValue('label').getValue();

            //Verify that all of them see the same value
            aura.test.assertEquals(labelValueThruComponent,'AttributeDefault');
            aura.test.assertEquals(labelValueThruComponent,labelValueThroughComponentApi);
            aura.test.assertEquals(labelValueThruComponent,labelValueByExpression);

            component.getAttributes().setValue('label','newLabel');
            var labelValueThroughComponentApi = component.getValue('{!v.label}').getValue();
            var labelValueByExpression = $A.expressionService.getValue(component, "{!v.label}").getValue();
            var labelValueThruComponent = component.getAttributes().getValue('label').getValue();

            //Verify that all of them see the same value
            aura.test.assertEquals(labelValueThruComponent,'newLabel');
            aura.test.assertEquals(labelValueThruComponent,labelValueThroughComponentApi);
            aura.test.assertEquals(labelValueThruComponent,labelValueByExpression);
        }

    },
    testVerifyCommitFunctionOnAttributes: {
        test: function(component){
            /**Attributes of a Component are stored as value objects
             * Verify that such value objects can be committed
             */
            var stringValue = component.getAttributes().getValue('label');
            aura.test.assertTrue(stringValue.getValue()==="AttributeDefault", "Value mis match between attribute value and retrieved value");
            stringValue.setValue('newString');

            aura.test.assertTrue(stringValue.getValue()==='newString', "getValue is not retrieving the latest value");
            aura.test.assertTrue(component.getAttributes().getValue('label').getPreviousValue()==='AttributeDefault', "getPreviousValue is not retrieving the previous value");
            //Commit a value
            component.getAttributes().getValue('label').commit();
            aura.test.assertTrue(component.getAttributes().getValue('label').getPreviousValue()==="newString", "Value was not committed");
        }

    },

    /**
     * Verify behavior of setting the value of an attribute that does not exist.
     *
     * Currently setting a non-existent attribute is a no-op, but after W-795118 is fixed, we should throw an Error.
     */
    testVerifySetValueNonExistentAttributes:{
        test: function(component){
            var attributeSet = component.getAttributes();
            var newValue = attributeSet.getValue('nonExistingAttribute');
            $A.test.assertFalse(newValue.isDefined(), 'A defined Value object was created');
            // TODO(W-795118): AttributeSet.setValues should assert that the attribute exists
            // try {
                attributeSet.setValue('nonExistingAttribute', 'blahhh');
                // $A.test.fail("Setting a non-existent attribute should throw error.");
            // } catch (e) {
                // $A.test.assertTrue(e.message.indexOf("Assertion Failed!: Unknown attribute") != -1,
                //        "Setting non-existent attribute did not throw expected Error.");
                $A.test.assertFalse(attributeSet.getValue('nonExistingAttribute').isDefined());
            // }
        }
    },

    testInvalidUseOfGetAttributes:{
        test: function(component){
            var attributeSet = component.getAttributes();
            var attrValue = attributeSet.getValue('label');
            //attrValue.getValue() is the actual usage of a wrapped value object
            var newBlankValue = attrValue.getValue('blah');
            aura.test.assertDefined(newBlankValue, 'A Value was not created');
        }
    }

})
<|endoftext|>


<commit_before>define([
  'intern!bdd',
  'intern/chai!expect',
  'platform/ultralight-platform.min'
], function(bdd, expect, platform) {
  var describe = bdd.describe.bind(bdd)
  var it = bdd.it.bind(bdd)

  describe('ultralight-platform', function() {

    it('shoud add document.registerElement', function() {
      expect(document).to.have.property('registerElement')
    })

    it('should allow a simple custom element to be registered', function() {
      var XOne = document.registerElement('x-one')

      var el = new XOne()
      document.body.appendChild(el);
      var nl  = document.querySelectorAll('x-one')

      expect(el).to.be.an.instanceof(Node)
      expect(el).to.be.an.instanceof(Element)
      expect(el).to.be.an.instanceof(HTMLElement)
      expect(nl.length).to.equal(1)

      document.body.removeChild(el)
      nl = document.querySelectorAll('x-one')
      expect(nl.length).to.equal(0)
    })

    it('should allow a custom element which explicitly sets it\'s prototype to HTMLElement', function() {
      var XTwo = document.registerElement('x-two', {
        prototype: Object.create(HTMLElement.prototype)
      })

      var el = new XTwo()
      document.body.appendChild(el)
      var nl = document.querySelectorAll('x-two')

      expect(el).to.be.an.instanceof(Node)
      expect(el).to.be.an.instanceof(Element)
      expect(el).to.be.an.instanceof(HTMLElement)
      expect(nl.length).to.equal(1)
      document.body.removeChild(el)
      nl = document.querySelectorAll('x-two')
      expect(nl.length).to.equal(0)
    })

    it('should allow you to extend native elements (create type extension custom elements)', function() {
      var XThree = document.registerElement('x-three', {
        prototype: Object.create(HTMLButtonElement.prototype),
        extends: 'button'
      })

      var el = new XThree()
      var div = document.createElement('div')
      div.innerHTML = '<button is="x-three"></button>'
      document.body.appendChild(div)
      var nl = document.querySelectorAll('button[is]')

      expect(el).to.be.an.instanceof(Node)
      expect(el).to.be.an.instanceof(Element)
      expect(el).to.be.an.instanceof(HTMLElement)
      expect(el).to.be.an.instanceof(HTMLButtonElement)
      expect(nl.length).to.equal(1)

      document.body.removeChild(div)
      nl = document.querySelectorAll('button[is]')
      expect(nl.length).to.equal(0)
    })

    it('should allow you to extend custom elements', function() {
      var XFour = document.registerElement('x-four', {
        prototype: Object.create(HTMLElement.prototype)
      })
      var XFive = document.registerElement('x-five', {
        prototype: Object.create(XFour.prototype)
        //extends: 'x-four'
      })

      var el = new XFive()
      document.body.appendChild(el)
      var nl = document.querySelectorAll('x-five')

      expect(el).to.be.an.instanceof(Node)
      expect(el).to.be.an.instanceof(Element)
      expect(el).to.be.an.instanceof(HTMLElement)
      expect(el).to.be.an.instanceof(XFour)
      expect(nl.length).to.equal(1)

      document.body.removeChild(el)
      nl = document.querySelectorAll('x-five')
      expect(nl.length).to.equal(0)
    })
  })

  describe('Instantiating custom tags', function() {

    it('should create custom elements by declaring them with the tag', function() {
      var XSix = document.registerElement('x-six')
      var div = document.createElement('div')
      div.innerHTML = '<x-six></x-six>'

      document.body.appendChild(div)
      var nl = document.querySelectorAll('x-six')
      expect(nl.length).to.equal(1)

      document.body.removeChild(div)
      nl = document.querySelectorAll('x-six')
      expect(nl.length).to.equal(0)
    })

    it('should create custom elements with DOM in JS', function() {
      document.registerElement('x-seven')
      var xseven = document.createElement('x-seven')

      document.body.appendChild(xseven)
      var nl = document.querySelectorAll('x-seven')
      expect(nl.length).to.equal(1)

      document.body.removeChild(xseven)
      nl = document.querySelectorAll('x-seven')
      expect(nl.length).to.equal(0)
    })

    it('should create custom elements with the new operator', function() {
      var XEight = document.registerElement('x-eight')
      var xeight = new XEight()

      document.body.appendChild(xeight)
      var nl = document.querySelectorAll('x-eight')
      expect(nl.length).to.equal(1)

      document.body.removeChild(xeight)
      nl = document.querySelectorAll('x-eight')
      expect(nl.length).to.equal(0)
    })
  })

  describe('Instantiating type extension elements', function() {

    it('should create type extention elements by declaring them with the tag', function() {

      var XNine = document.registerElement('x-nine', {
        prototype: Object.create(HTMLButtonElement.prototype),
        extends: 'button'
      })

      var div = document.createElement('div')
      div.innerHTML = '<button is="x-nine"></button>'
      document.body.appendChild(div)

      var nl = document.querySelectorAll('button[is=x-nine]')
      expect(nl.length).to.equal(1)

      document.body.removeChild(div)
      nl = document.querySelectorAll('button[is=x-nine]')
      expect(nl.length).to.equal(0)
    })

    it('should create type extention elements with DOM in JS', function() {
      var XTen = document.registerElement('x-ten', {
        prototype: Object.create(HTMLButtonElement.prototype),
        extends: 'button'
      })

      var xten = document.createElement('button', 'x-ten')
      document.body.appendChild(xten)
      var nl = document.querySelectorAll('button[is=x-ten]')
      expect(nl.length).to.equal(1)

      document.body.removeChild(xten)
      nl = document.querySelectorAll('button[is=x-ten]')
      expect(nl.length).to.equal(0)
    })

    it('should create type extension elements with the new operator', function() {
      var XEleven = document.registerElement('x-eleven', {
        prototype: Object.create(HTMLButtonElement.prototype),
        extends: 'button'
      })

      var xeleven = new XEleven()
      document.body.appendChild(xeleven)
      var nl = document.querySelectorAll('button[is=x-eleven]')
      expect(nl.length).to.equal(1)

      document.body.removeChild(xeleven)
      nl = document.querySelectorAll('button[is=x-eleven]')
      expect(nl.length).to.equal(0)
    })
  })

  describe('Adding properties and methods', function() {

    it('should create a property assigned to the prototype', function() {

      var XTwelveProto = Object.create(HTMLElement.prototype)
      XTwelveProto.foo = 'foo'
      var XTwelve = document.registerElement('x-twelve', {
        prototype: XTwelveProto
      })
      var xtwelve = document.createElement('x-twelve')
      document.body.appendChild(xtwelve)

      var nl = document.querySelectorAll('x-twelve')
      expect(nl[0].foo).to.equal('foo')

      document.body.removeChild(xtwelve)
      nl = document.querySelectorAll('x-twelve')
      expect(nl.length).to.equal(0)
    })

    it('should create a method assigned to the prototype', function() {

      var XThirteenProto = Object.create(HTMLElement.prototype)
      XThirteenProto.foo = function() {return 'foo'}
      var XThirteen = document.registerElement('x-thirteen', {
        prototype: XThirteenProto
      })
      var xthirteen = document.createElement('x-thirteen')
      document.body.appendChild(xthirteen)

      var nl = document.querySelectorAll('x-thirteen')
      expect(nl[0].foo()).to.equal('foo')

      document.body.removeChild(xthirteen)
      nl = document.querySelectorAll('x-thirteen')
      expect(nl.length).to.equal(0)
    })

    it('should create a property using Object.defineProperty', function() {
      var XFourteenProto = Object.create(HTMLElement.prototype)
      Object.defineProperty(XFourteenProto, 'bar', {value: 'bar'})
      var XFourteen = document.registerElement('x-fourteen', {
        prototype: XFourteenProto
      })
      var xfourteen = document.createElement('x-fourteen')
      document.body.appendChild(xfourteen)

      var nl = document.querySelectorAll('x-fourteen')
      expect(nl[0].bar).to.equal('bar')

      document.body.removeChild(xfourteen)
      nl = document.querySelectorAll('x-fourteen')
      expect(nl.length).to.equal(0)
    })

    it('should create elements in Object.defineProperties style', function() {
      var XFifteen = document.registerElement('x-fifteen', {
        prototype: Object.create(HTMLElement.prototype, {
          foo: {
            get: function() {return 'foo'}
          },
          bar: {
            value: function() {
              return 'bar'
            }
          }
        })
      })

      var xfifteen = document.createElement('x-fifteen')
      document.body.appendChild(xfifteen)
      var nl = document.querySelectorAll('x-fifteen')

      expect(nl.length).to.equal(1)
      expect(nl[0]['foo']).to.equal('foo')
      expect(nl[0].bar()).to.equal('bar')

      document.body.removeChild(xfifteen)
      nl = document.querySelectorAll('x-fifteen')
      expect(nl.length).to.equal(0)
    })
  })

  describe('Lifecycle callback methods', function() {

    it('supports createdCallback', function() {
      var XSixteenProto = Object.create(HTMLElement.prototype)
      XSixteenProto.createdCallback = function() {
        XSixteenProto.foo = 'foo'
      }
      var XSixteen = document.registerElement('x-sixteen', {prototype: XSixteenProto})
      var xsixteen = document.createElement('x-sixteen')
      expect(xsixteen.foo).to.equal('foo')
    })

    it('supports attachedCallback', function() {
      var dfd = this.async(100)

      var XSeventeenProto = Object.create(HTMLElement.prototype)
      XSeventeenProto.attachedCallback = function() {
        XSeventeenProto.foo = 'foo'
      }
      var XSeventeen = document.registerElement('x-seventeen', {prototype: XSeventeenProto})

      var xseventeen = document.createElement('x-seventeen')
      expect(xseventeen.foo).to.not.exist
      document.body.appendChild(xseventeen)
      setTimeout(dfd.callback(function() {
        expect(xseventeen.foo).to.equal('foo')
      }), 10)
    })

    it('supports detatchedCallback', function() {
      var dfd = this.async(100);

      var XEighteenProto = Object.create(HTMLElement.prototype)
      XEighteenProto.detachedCallback = function() {
        XEighteenProto.foo = 'foo'
      }
      var XEighteen = document.registerElement('x-eighteen', {prototype: XEighteenProto})

      var xeighteen = document.createElement('x-eighteen')
      expect(xeighteen.foo).to.not.exist
      document.body.appendChild(xeighteen)
      expect(xeighteen.foo).to.not.exist
      document.body.removeChild(xeighteen)
      setTimeout(dfd.callback(function() {
        expect(xeighteen.foo).to.equal('foo')
      }), 10)
    })

    it('supports attributeChangedCallback', function() {
      var XNineteenProto = Object.create(HTMLElement.prototype)
      XNineteenProto.attributeChangedCallback = function(attrName, oldVal, newVal) {
        if (attrName === 'foo') {
          expect(oldVal).to.equal('foo')
          expect(newVal).to.equal('bar')
        }
      }
      var XNineteen = document.registerElement('x-nineteen', {prototype: XNineteenProto})
      var div = document.createElement('div')
      div.innerHTML = '<x-nineteen foo="foo"></x-nineteen>'
      document.body.appendChild(div)
      var nl = document.querySelectorAll('x-nineteen')
      nl[0].setAttribute('foo', 'bar')
    })
  })

  describe('Custom Events', function() {

    it('has custom event constructor', function() {
      expect(CustomEvent).to.exist
    })

    it('works with custom elements', function() {
      var dfd = this.async(100)
      document.registerElement('x-ce')
      var el = document.createElement('x-ce')
      el.addEventListener('foo', dfd.callback(function(e) {
        expect(true).to.equal(true)
        expect(e).to.exist
        expect(e.type).to.equal('foo')
      }))
      var event = new CustomEvent('foo')
      el.dispatchEvent(event)
    })
  })
})
<commit_msg>skip extending custom element tests until ie9/10 problem is fixed<commit_after>define([
  'intern!bdd',
  'intern/chai!expect',
  'platform/ultralight-platform.min'
], function(bdd, expect, platform) {
  var describe = bdd.describe.bind(bdd)
  var it = bdd.it.bind(bdd)

  describe('ultralight-platform', function() {

    it('shoud add document.registerElement', function() {
      expect(document).to.have.property('registerElement')
    })

    it('should allow a simple custom element to be registered', function() {
      var XOne = document.registerElement('x-one')

      var el = new XOne()
      document.body.appendChild(el);
      var nl  = document.querySelectorAll('x-one')

      expect(el).to.be.an.instanceof(Node)
      expect(el).to.be.an.instanceof(Element)
      expect(el).to.be.an.instanceof(HTMLElement)
      expect(nl.length).to.equal(1)

      document.body.removeChild(el)
      nl = document.querySelectorAll('x-one')
      expect(nl.length).to.equal(0)
    })

    it('should allow a custom element which explicitly sets it\'s prototype to HTMLElement', function() {
      var XTwo = document.registerElement('x-two', {
        prototype: Object.create(HTMLElement.prototype)
      })

      var el = new XTwo()
      document.body.appendChild(el)
      var nl = document.querySelectorAll('x-two')

      expect(el).to.be.an.instanceof(Node)
      expect(el).to.be.an.instanceof(Element)
      expect(el).to.be.an.instanceof(HTMLElement)
      expect(nl.length).to.equal(1)
      document.body.removeChild(el)
      nl = document.querySelectorAll('x-two')
      expect(nl.length).to.equal(0)
    })

    it('should allow you to extend native elements (create type extension custom elements)', function() {
      var XThree = document.registerElement('x-three', {
        prototype: Object.create(HTMLButtonElement.prototype),
        extends: 'button'
      })

      var el = new XThree()
      var div = document.createElement('div')
      div.innerHTML = '<button is="x-three"></button>'
      document.body.appendChild(div)
      var nl = document.querySelectorAll('button[is]')

      expect(el).to.be.an.instanceof(Node)
      expect(el).to.be.an.instanceof(Element)
      expect(el).to.be.an.instanceof(HTMLElement)
      expect(el).to.be.an.instanceof(HTMLButtonElement)
      expect(nl.length).to.equal(1)

      document.body.removeChild(div)
      nl = document.querySelectorAll('button[is]')
      expect(nl.length).to.equal(0)
    })

    it('should allow you to extend custom elements', function() {

      this.skip()

      var XFour = document.registerElement('x-four', {
        prototype: Object.create(HTMLElement.prototype)
      })
      var XFive = document.registerElement('x-five', {
        prototype: Object.create(XFour.prototype),
      })

      var el = new XFive()
      document.body.appendChild(el)
      var nl = document.querySelectorAll('x-five')

      expect(el).to.be.an.instanceof(Node)
      expect(el).to.be.an.instanceof(Element)
      expect(el).to.be.an.instanceof(HTMLElement)
      expect(el).to.be.an.instanceof(XFour)
      expect(nl.length).to.equal(1)

      document.body.removeChild(el)
      nl = document.querySelectorAll('x-five')
      expect(nl.length).to.equal(0)
    })
  })

  describe('Instantiating custom tags', function() {

    it('should create custom elements by declaring them with the tag', function() {
      var XSix = document.registerElement('x-six')
      var div = document.createElement('div')
      div.innerHTML = '<x-six></x-six>'

      document.body.appendChild(div)
      var nl = document.querySelectorAll('x-six')
      expect(nl.length).to.equal(1)

      document.body.removeChild(div)
      nl = document.querySelectorAll('x-six')
      expect(nl.length).to.equal(0)
    })

    it('should create custom elements with DOM in JS', function() {
      document.registerElement('x-seven')
      var xseven = document.createElement('x-seven')

      document.body.appendChild(xseven)
      var nl = document.querySelectorAll('x-seven')
      expect(nl.length).to.equal(1)

      document.body.removeChild(xseven)
      nl = document.querySelectorAll('x-seven')
      expect(nl.length).to.equal(0)
    })

    it('should create custom elements with the new operator', function() {
      var XEight = document.registerElement('x-eight')
      var xeight = new XEight()

      document.body.appendChild(xeight)
      var nl = document.querySelectorAll('x-eight')
      expect(nl.length).to.equal(1)

      document.body.removeChild(xeight)
      nl = document.querySelectorAll('x-eight')
      expect(nl.length).to.equal(0)
    })
  })

  describe('Instantiating type extension elements', function() {

    it('should create type extention elements by declaring them with the tag', function() {

      var XNine = document.registerElement('x-nine', {
        prototype: Object.create(HTMLButtonElement.prototype),
        extends: 'button'
      })

      var div = document.createElement('div')
      div.innerHTML = '<button is="x-nine"></button>'
      document.body.appendChild(div)

      var nl = document.querySelectorAll('button[is=x-nine]')
      expect(nl.length).to.equal(1)

      document.body.removeChild(div)
      nl = document.querySelectorAll('button[is=x-nine]')
      expect(nl.length).to.equal(0)
    })

    it('should create type extention elements with DOM in JS', function() {
      var XTen = document.registerElement('x-ten', {
        prototype: Object.create(HTMLButtonElement.prototype),
        extends: 'button'
      })

      var xten = document.createElement('button', 'x-ten')
      document.body.appendChild(xten)
      var nl = document.querySelectorAll('button[is=x-ten]')
      expect(nl.length).to.equal(1)

      document.body.removeChild(xten)
      nl = document.querySelectorAll('button[is=x-ten]')
      expect(nl.length).to.equal(0)
    })

    it('should create type extension elements with the new operator', function() {
      var XEleven = document.registerElement('x-eleven', {
        prototype: Object.create(HTMLButtonElement.prototype),
        extends: 'button'
      })

      var xeleven = new XEleven()
      document.body.appendChild(xeleven)
      var nl = document.querySelectorAll('button[is=x-eleven]')
      expect(nl.length).to.equal(1)

      document.body.removeChild(xeleven)
      nl = document.querySelectorAll('button[is=x-eleven]')
      expect(nl.length).to.equal(0)
    })
  })

  describe('Adding properties and methods', function() {

    it('should create a property assigned to the prototype', function() {

      var XTwelveProto = Object.create(HTMLElement.prototype)
      XTwelveProto.foo = 'foo'
      var XTwelve = document.registerElement('x-twelve', {
        prototype: XTwelveProto
      })
      var xtwelve = document.createElement('x-twelve')
      document.body.appendChild(xtwelve)

      var nl = document.querySelectorAll('x-twelve')
      expect(nl[0].foo).to.equal('foo')

      document.body.removeChild(xtwelve)
      nl = document.querySelectorAll('x-twelve')
      expect(nl.length).to.equal(0)
    })

    it('should create a method assigned to the prototype', function() {

      var XThirteenProto = Object.create(HTMLElement.prototype)
      XThirteenProto.foo = function() {return 'foo'}
      var XThirteen = document.registerElement('x-thirteen', {
        prototype: XThirteenProto
      })
      var xthirteen = document.createElement('x-thirteen')
      document.body.appendChild(xthirteen)

      var nl = document.querySelectorAll('x-thirteen')
      expect(nl[0].foo()).to.equal('foo')

      document.body.removeChild(xthirteen)
      nl = document.querySelectorAll('x-thirteen')
      expect(nl.length).to.equal(0)
    })

    it('should create a property using Object.defineProperty', function() {
      var XFourteenProto = Object.create(HTMLElement.prototype)
      Object.defineProperty(XFourteenProto, 'bar', {value: 'bar'})
      var XFourteen = document.registerElement('x-fourteen', {
        prototype: XFourteenProto
      })
      var xfourteen = document.createElement('x-fourteen')
      document.body.appendChild(xfourteen)

      var nl = document.querySelectorAll('x-fourteen')
      expect(nl[0].bar).to.equal('bar')

      document.body.removeChild(xfourteen)
      nl = document.querySelectorAll('x-fourteen')
      expect(nl.length).to.equal(0)
    })

    it('should create elements in Object.defineProperties style', function() {
      var XFifteen = document.registerElement('x-fifteen', {
        prototype: Object.create(HTMLElement.prototype, {
          foo: {
            get: function() {return 'foo'}
          },
          bar: {
            value: function() {
              return 'bar'
            }
          }
        })
      })

      var xfifteen = document.createElement('x-fifteen')
      document.body.appendChild(xfifteen)
      var nl = document.querySelectorAll('x-fifteen')

      expect(nl.length).to.equal(1)
      expect(nl[0]['foo']).to.equal('foo')
      expect(nl[0].bar()).to.equal('bar')

      document.body.removeChild(xfifteen)
      nl = document.querySelectorAll('x-fifteen')
      expect(nl.length).to.equal(0)
    })
  })

  describe('Lifecycle callback methods', function() {

    it('supports createdCallback', function() {
      var dfd = this.async(1000)

      var XSixteenProto = Object.create(HTMLElement.prototype)
      XSixteenProto.createdCallback = dfd.callback(function() {
        XSixteenProto.foo = 'foo'
        expect(XSixteenProto.foo).to.equal('foo')
      })
      var XSixteen = document.registerElement('x-sixteen', {prototype: XSixteenProto})
      var xsixteen = document.createElement('x-sixteen')
    })

    it('supports attachedCallback', function() {
      var dfd = this.async(1000)

      var XSeventeenProto = Object.create(HTMLElement.prototype)
      XSeventeenProto.attachedCallback = dfd.callback(function() {
        XSeventeenProto.foo = 'foo'
        expect(XSeventeenProto.foo).to.equal('foo')
      })
      var XSeventeen = document.registerElement('x-seventeen', {prototype: XSeventeenProto})

      var xseventeen = document.createElement('x-seventeen')
      expect(xseventeen.foo).to.not.exist
      document.body.appendChild(xseventeen)
    })

    it('supports detatchedCallback', function() {
      var dfd = this.async(1000);

      var XEighteenProto = Object.create(HTMLElement.prototype)
      XEighteenProto.detachedCallback = dfd.callback(function() {
        XEighteenProto.foo = 'foo'
        expect(XEighteenProto.foo).to.equal('foo')
      })
      var XEighteen = document.registerElement('x-eighteen', {prototype: XEighteenProto})

      var xeighteen = document.createElement('x-eighteen')
      expect(xeighteen.foo).to.not.exist
      document.body.appendChild(xeighteen)
      expect(xeighteen.foo).to.not.exist
      document.body.removeChild(xeighteen)
    })

    it('supports attributeChangedCallback', function() {
      var XNineteenProto = Object.create(HTMLElement.prototype)
      XNineteenProto.attributeChangedCallback = function(attrName, oldVal, newVal) {
        if (attrName === 'foo') {
          expect(oldVal).to.equal('foo')
          expect(newVal).to.equal('bar')
        }
      }
      var XNineteen = document.registerElement('x-nineteen', {prototype: XNineteenProto})
      var div = document.createElement('div')
      div.innerHTML = '<x-nineteen foo="foo"></x-nineteen>'
      document.body.appendChild(div)
      var nl = document.querySelectorAll('x-nineteen')
      nl[0].setAttribute('foo', 'bar')
    })
  })

  describe('Custom Events', function() {

    it('has custom event constructor', function() {
      expect(CustomEvent).to.exist
    })

    it('works with custom elements', function() {
      var dfd = this.async(100)
      document.registerElement('x-ce')
      var el = document.createElement('x-ce')
      el.addEventListener('foo', dfd.callback(function(e) {
        expect(true).to.equal(true)
        expect(e).to.exist
        expect(e.type).to.equal('foo')
      }))
      var event = new CustomEvent('foo')
      el.dispatchEvent(event)
    })
  })
})
<|endoftext|>


<commit_before>/* global describe, it */

'use strict';

(function () {

  var expect = require('chai').expect;

  var Program = require('../src/program');
  var Command = require('../src/command');
  var KWArg = require('../src/kwarg');
  var Flag = require('../src/flag');
  var Arg = require('../src/arg');
  var utils = require('../src/utils');
  var Required = require('../src/required');
  var RequireAll = require('../src/require-all');
  var RequireAny = require('../src/require-any');

  describe('utils.js', function () {

    it('should exist', function () {
      expect(utils).to.be.ok;
    });

    describe('argsToArray', function () {

      it('should convert arguments to an array', function () {
        function fn () {
          var args = utils.argsToArray(arguments);

          expect(Array.isArray(args)).to.be.true;
          expect(args).not.to.equal(arguments);
        }

        fn('foo', 'bar');
      });

    });

    describe('getNodeProperties', function () {

      it('should throw an error for invalid children', function () {
        var anError = /invalid/i;
        var child1 = Command('child1');
        var child2 = 'invalid';

        function fn () {
          utils.getNodeProperties(arguments, true);
        }

        expect(fn.bind(null, 'foo', {alias: 'bar'}, child1, child2)).to.throw(anError);
      });

      it('should throw an error for invalid types of children', function () {
        var anError = /invalid/i;
        var child1 = Command('child1');
        var child2 = Program('invalid');

        function fn () {
          utils.getNodeProperties(arguments, true);
        }

        expect(fn.bind(null, 'foo', {alias: 'bar'}, child1, child2)).to.throw(anError);
      });

      it('should get a node\'s properties from the supplied arguments (with children)', function () {
        var child1 = Command('child1');
        var child2 = Command('child2');
        var child3 = Command('child3');

        function fn () {
          var properties = utils.getNodeProperties(arguments, true);

          expect(properties).to.be.ok;
          expect(properties).to.eql({
            name: 'foo',
            options: {
              alias: 'bar'
            },
            children: [child1, child2, child3],
            requireAll: [],
            requireAny: []
          });
        }

        fn('foo', {alias: 'bar'}, child1, child2, child3);
      });

      it('should get a node\'s properties from the supplied arguments (with required children)', function () {
        var child1 = Command('child1');
        var child2 = Command('child2');
        var child3 = Command('child3');
        var child4 = Command('child4');
        var child5 = Command('child5');
        var child6 = Command('child6');
        var child7 = Command('child7');

        function fn () {
          var properties = utils.getNodeProperties(arguments, true);

          expect(properties).to.be.ok;
          expect(properties).to.eql({
            name: 'foo',
            options: {
              alias: 'bar'
            },
            children: [child1, child2, child3, child4, child5, child6, child7],
            requireAll: [child2, child3, child4],
            requireAny: [child5, child6]
          });
        }

        fn(
          'foo',
          {alias: 'bar'},
          child1, Required(child2), RequireAll(child3, child4), RequireAny(child5, child6), child7
        );
      });

      it('should get a node\'s properties from the supplied arguments (without children)', function () {
        function fn () {
          var properties = utils.getNodeProperties(arguments);

          expect(properties).to.be.ok;
          expect(properties).to.eql({
            name: 'foo',
            options: {
              alias: 'bar'
            }
          });
        }

        fn('foo', {alias: 'bar'});
      });

      it('should should throw an error if children are provided, but not welcome', function () {
        var anError = /children/i;
        var child = Command('child');

        function fn () {
          utils.getNodeProperties(arguments);
        }

        expect(fn.bind(null, 'foo', {alias: 'bar'}, child)).to.throw(anError);
      });

    });

    describe('find', function () {

      var arr = [1, 2, 3, 4, 5];

      it('should return null if no items match the predicate', function () {
        var result = utils.find(arr, function (value) {
          return value > 5;
        });

        expect(result).to.be.null;
      });

      it('should return the value if an item matches the predicate', function () {
        var result = utils.find(arr, function (value) {
          return value < 4 && value > 2;
        });

        expect(result).to.equal(3);
      });

    });

    describe('each', function () {

      var arr = [1, 2, 3, 4, 5];

      it('should call the provided function for each item in an array', function () {
        var count = 0;

        utils.each(arr, function (value, index) {
          expect(index).to.equal(count);
          expect(value).to.equal(arr[index]);
          count += 1;
        });

        expect(count).to.equal(5);
      });

    });

    describe('any', function () {

      var arr = [1, 2, 3, 4, 5];

      it('should return true if any items match the predicate', function () {
        expect(utils.any(arr, function (value) {
          return value === 3;
        })).to.be.true;

        expect(utils.any(arr, function (value) {
          return value === 10;
        })).to.be.false;
      });

    });

    describe('sum', function () {

      it('should sum the values in an array', function () {
        expect(utils.sum([1, 2, 3, 4])).to.equal(10);
        expect(utils.sum([1, 2, 3, 4, 5])).to.equal(15);
        expect(utils.sum([3, 4, 2])).to.equal(9);
      });

    });

    describe('createHelp', function () {

      it('should create a basic error message', function () {
        var schema = Command('test');
        var error = 'An error';

        var expected = [
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

      it('should create help with usage text', function () {
        var schema = Command('test', {usage: 'How to use'});
        var error = 'An error';

        var expected = [
          '',
          '  Usage: How to use',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

      it('should create help with commands text', function () {
        var schema = Command('test', null, Command('sub', {alias: 's', description: 'Description'}));
        var error = 'An error';

        var expected = [
          '',
          '  Commands:',
          '    sub, s  Description',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        var result = utils.createHelp(schema, error);

        expect(result).to.equal(expected);
      });

      it('should create help with options text', function () {
        var schema = Command(
          'test',
          null,
          Arg(
            'arg',
            {description: 'Desc 1'}
          ),
          Flag(
            'flag',
            {alias: 'f', description: 'Desc 2'}
          )
        );
        var error = 'An error';

        var expected = [
          '',
          '  Options:',
          '    <arg>       Desc 1',
          '    --flag, -f  Desc 2',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

      it('should create help with options text with types', function () {
        var schema = Command(
          'test',
          null,
          Arg(
            'arg',
            {description: 'Desc 1', type: 'string'}
          ),
          KWArg(
            'kwarg',
            {alias: 'k', description: 'Desc 2', type: 'number'}
          )
        );
        var error = 'An error';

        var expected = [
          '',
          '  Options:',
          '    <arg>        Desc 1                                                 [string]',
          '    --kwarg, -k  Desc 2                                                 [number]',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

      it('should create help with examples text', function () {
        var schema = Command(
          'test',
          {examples: ['Just like this']}
        );
        var error = 'An error';

        var expected = [
          '',
          '  Examples:',
          '    Just like this',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

      it('should create some complex help text', function () {
        var schema = Command(
          'test',
          {alias: 't', description: 'A command', usage: 'Used like this', examples: ['Example 1', 'Example 2']},
          Arg(
            'arg',
            {description: 'Desc 1', type: 'string'}
          ),
          Flag(
            'flag',
            {alias: 'f', description: 'Desc 2'}
          ),
          KWArg(
            'kwarg',
            {alias: 'k', description: 'Desc 3', type: 'boolean'}
          ),
          Command(
            'sub',
            {description: 'A sub command'}
          )
        );
        var error = 'An error';

        var expected = [
          '',
          '  Usage: Used like this',
          '',
          '  Commands:',
          '    sub  A sub command',
          '',
          '  Options:',
          '    <arg>        Desc 1                                                 [string]',
          '    --flag, -f   Desc 2',
          '    --kwarg, -k  Desc 3                                                [boolean]',
          '',
          '  Examples:',
          '    Example 1',
          '    Example 2',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

    });

    describe('formatTable', function () {

      it('should format a table with 2 columns, and wrap the last column (commands)', function () {
        var table = [
          ['build', 'Build your project'],
          ['install, i', 'Install new dependencies, or dependencies saved in your package.json']
        ];

        var expected = [
          '    build       Build your project',
          '    install, i  Install new dependencies, or dependencies saved in your',
          '                package.json'
        ].join('\n');

        var result = utils.formatTable(table, {alignRight: [], wrap: [1]});

        expect(result).to.equal(expected);
      });

      it('should format a table with 3 columns, and wrap the 2nd column (options)', function () {
        var table = [
          ['--help', 'Display help & usage information', ''],
          ['--transform, -t', 'Plugin to use when compiling your javascript blah blah blah', '[string]'],
          ['--version, -v', 'Display version number', '']
        ];

        var expected = [
          '    --help           Display help & usage information',
          '    --transform, -t  Plugin to use when compiling your javascript blah  [string]',
          '                     blah blah',
          '    --version, -v    Display version number'
        ].join('\n');

        var result = utils.formatTable(table, {alignRight: [2], wrap: [1]});

        expect(result).to.equal(expected);
      });

      it('should format a table with 3 columns, and wrap the last 2, and right align the final column', function () {
        var table = [
          [
            'line1',
            'Some text that should be wrapped',
            'Some right aligned text that will be wrappped'
          ],
          [
            'line2, l2',
            'Some incidentally wrapped text',
            'Some right aligned text'
          ],
          [
            'line3, l3',
            'No wrap',
            'Right aligned'
          ],
          [
            'line4, l4',
            'Another line of text that should be wrapped',
            'Some more right aligned text that will be wrapped onto 3 different lines because it\'s really quite long'
          ],
          [
            'line5, l5',
            'Ahyphenatedwordwillbewrapped',
            'Anotherhyphenatedwordwillbewrappedbuthastobelongerbecausethiscolumniswider'
          ]
        ];

        var expected = [
          '    line1      Some text that               Some right aligned text that will be',
          '               should be wrapped                                        wrappped',
          '    line2, l2  Some incidentally                         Some right aligned text',
          '               wrapped text',
          '    line3, l3  No wrap                                             Right aligned',
          '    line4, l4  Another line of         Some more right aligned text that will be',
          '               text that should be   wrapped onto 3 different lines because it\'s',
          '               wrapped                                         really quite long',
          '    line5, l5  Ahyphenatedwordwil-  Anotherhyphenatedwordwillbewrappedbuthastob-',
          '               lbewrapped                        elongerbecausethiscolumniswider'
        ].join('\n');

        var result = utils.formatTable(table, {alignRight: [2], wrap: [1, 2]});

        expect(result).to.equal(expected);
      });

      it('should format a table with 3 columns and wrap them all', function () {
        var table = [
          [
            '40 character string la da da da da... da',
            'Another 40 character string la da da doo',
            'A super long 80 character string that will still be wrapped equal to the others!'
          ]
        ];

        // 80 - 4 - 2 - 2 = 72
        // 72 / 4 = 18
        // Column 1 & 2 get 18 chars, and column 3 gets 36

        var expected = [
          '    40 character        Another 40          A super long 80 character string',
          '    string la da da da  character string    that will still be wrapped equal to',
          '    da... da            la da da doo        the others!'
        ].join('\n');

        var result = utils.formatTable(table, {alignRight: [], wrap: [0, 1, 2]});

        expect(result).to.equal(expected);
      });

    });

  });

})();
<commit_msg>Ensure required & children strictly equal children<commit_after>/* global describe, it */

'use strict';

(function () {

  var expect = require('chai').expect;

  var Program = require('../src/program');
  var Command = require('../src/command');
  var KWArg = require('../src/kwarg');
  var Flag = require('../src/flag');
  var Arg = require('../src/arg');
  var utils = require('../src/utils');
  var Required = require('../src/required');
  var RequireAll = require('../src/require-all');
  var RequireAny = require('../src/require-any');

  describe('utils.js', function () {

    it('should exist', function () {
      expect(utils).to.be.ok;
    });

    describe('argsToArray', function () {

      it('should convert arguments to an array', function () {
        function fn () {
          var args = utils.argsToArray(arguments);

          expect(Array.isArray(args)).to.be.true;
          expect(args).not.to.equal(arguments);
        }

        fn('foo', 'bar');
      });

    });

    describe('getNodeProperties', function () {

      it('should throw an error for invalid children', function () {
        var anError = /invalid/i;
        var child1 = Command('child1');
        var child2 = 'invalid';

        function fn () {
          utils.getNodeProperties(arguments, true);
        }

        expect(fn.bind(null, 'foo', {alias: 'bar'}, child1, child2)).to.throw(anError);
      });

      it('should throw an error for invalid types of children', function () {
        var anError = /invalid/i;
        var child1 = Command('child1');
        var child2 = Program('invalid');

        function fn () {
          utils.getNodeProperties(arguments, true);
        }

        expect(fn.bind(null, 'foo', {alias: 'bar'}, child1, child2)).to.throw(anError);
      });

      it('should get a node\'s properties from the supplied arguments (with children)', function () {
        var child1 = Command('child1');
        var child2 = Command('child2');
        var child3 = Command('child3');

        function fn () {
          var properties = utils.getNodeProperties(arguments, true);

          expect(properties).to.be.ok;
          expect(properties).to.eql({
            name: 'foo',
            options: {
              alias: 'bar'
            },
            children: [child1, child2, child3],
            requireAll: [],
            requireAny: []
          });
        }

        fn('foo', {alias: 'bar'}, child1, child2, child3);
      });

      it('should get a node\'s properties from the supplied arguments (with required children)', function () {
        var child1 = Command('child1');
        var child2 = Command('child2');
        var child3 = Command('child3');
        var child4 = Command('child4');
        var child5 = Command('child5');
        var child6 = Command('child6');
        var child7 = Command('child7');

        function fn () {
          var properties = utils.getNodeProperties(arguments, true);

          expect(properties).to.be.ok;
          expect(properties).to.eql({
            name: 'foo',
            options: {
              alias: 'bar'
            },
            children: [child1, child2, child3, child4, child5, child6, child7],
            requireAll: [child2, child3, child4],
            requireAny: [child5, child6]
          });

          expect(properties.children[0]).to.equal(child1);
          expect(properties.children[3]).to.equal(child4);

          expect(properties.requireAll[1]).to.equal(child3);
          expect(properties.requireAny[0]).to.equal(child5);
        }

        fn(
          'foo',
          {alias: 'bar'},
          child1, Required(child2), RequireAll(child3, child4), RequireAny(child5, child6), child7
        );
      });

      it('should get a node\'s properties from the supplied arguments (without children)', function () {
        function fn () {
          var properties = utils.getNodeProperties(arguments);

          expect(properties).to.be.ok;
          expect(properties).to.eql({
            name: 'foo',
            options: {
              alias: 'bar'
            }
          });
        }

        fn('foo', {alias: 'bar'});
      });

      it('should should throw an error if children are provided, but not welcome', function () {
        var anError = /children/i;
        var child = Command('child');

        function fn () {
          utils.getNodeProperties(arguments);
        }

        expect(fn.bind(null, 'foo', {alias: 'bar'}, child)).to.throw(anError);
      });

    });

    describe('find', function () {

      var arr = [1, 2, 3, 4, 5];

      it('should return null if no items match the predicate', function () {
        var result = utils.find(arr, function (value) {
          return value > 5;
        });

        expect(result).to.be.null;
      });

      it('should return the value if an item matches the predicate', function () {
        var result = utils.find(arr, function (value) {
          return value < 4 && value > 2;
        });

        expect(result).to.equal(3);
      });

    });

    describe('each', function () {

      var arr = [1, 2, 3, 4, 5];

      it('should call the provided function for each item in an array', function () {
        var count = 0;

        utils.each(arr, function (value, index) {
          expect(index).to.equal(count);
          expect(value).to.equal(arr[index]);
          count += 1;
        });

        expect(count).to.equal(5);
      });

    });

    describe('any', function () {

      var arr = [1, 2, 3, 4, 5];

      it('should return true if any items match the predicate', function () {
        expect(utils.any(arr, function (value) {
          return value === 3;
        })).to.be.true;

        expect(utils.any(arr, function (value) {
          return value === 10;
        })).to.be.false;
      });

    });

    describe('sum', function () {

      it('should sum the values in an array', function () {
        expect(utils.sum([1, 2, 3, 4])).to.equal(10);
        expect(utils.sum([1, 2, 3, 4, 5])).to.equal(15);
        expect(utils.sum([3, 4, 2])).to.equal(9);
      });

    });

    describe('createHelp', function () {

      it('should create a basic error message', function () {
        var schema = Command('test');
        var error = 'An error';

        var expected = [
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

      it('should create help with usage text', function () {
        var schema = Command('test', {usage: 'How to use'});
        var error = 'An error';

        var expected = [
          '',
          '  Usage: How to use',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

      it('should create help with commands text', function () {
        var schema = Command('test', null, Command('sub', {alias: 's', description: 'Description'}));
        var error = 'An error';

        var expected = [
          '',
          '  Commands:',
          '    sub, s  Description',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        var result = utils.createHelp(schema, error);

        expect(result).to.equal(expected);
      });

      it('should create help with options text', function () {
        var schema = Command(
          'test',
          null,
          Arg(
            'arg',
            {description: 'Desc 1'}
          ),
          Flag(
            'flag',
            {alias: 'f', description: 'Desc 2'}
          )
        );
        var error = 'An error';

        var expected = [
          '',
          '  Options:',
          '    <arg>       Desc 1',
          '    --flag, -f  Desc 2',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

      it('should create help with options text with types', function () {
        var schema = Command(
          'test',
          null,
          Arg(
            'arg',
            {description: 'Desc 1', type: 'string'}
          ),
          KWArg(
            'kwarg',
            {alias: 'k', description: 'Desc 2', type: 'number'}
          )
        );
        var error = 'An error';

        var expected = [
          '',
          '  Options:',
          '    <arg>        Desc 1                                                 [string]',
          '    --kwarg, -k  Desc 2                                                 [number]',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

      it('should create help with examples text', function () {
        var schema = Command(
          'test',
          {examples: ['Just like this']}
        );
        var error = 'An error';

        var expected = [
          '',
          '  Examples:',
          '    Just like this',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

      it('should create some complex help text', function () {
        var schema = Command(
          'test',
          {alias: 't', description: 'A command', usage: 'Used like this', examples: ['Example 1', 'Example 2']},
          Arg(
            'arg',
            {description: 'Desc 1', type: 'string'}
          ),
          Flag(
            'flag',
            {alias: 'f', description: 'Desc 2'}
          ),
          KWArg(
            'kwarg',
            {alias: 'k', description: 'Desc 3', type: 'boolean'}
          ),
          Command(
            'sub',
            {description: 'A sub command'}
          )
        );
        var error = 'An error';

        var expected = [
          '',
          '  Usage: Used like this',
          '',
          '  Commands:',
          '    sub  A sub command',
          '',
          '  Options:',
          '    <arg>        Desc 1                                                 [string]',
          '    --flag, -f   Desc 2',
          '    --kwarg, -k  Desc 3                                                [boolean]',
          '',
          '  Examples:',
          '    Example 1',
          '    Example 2',
          '',
          '  An error',
          '',
          ''
        ].join('\n');

        expect(utils.createHelp(schema, error)).to.equal(expected);
      });

    });

    describe('formatTable', function () {

      it('should format a table with 2 columns, and wrap the last column (commands)', function () {
        var table = [
          ['build', 'Build your project'],
          ['install, i', 'Install new dependencies, or dependencies saved in your package.json']
        ];

        var expected = [
          '    build       Build your project',
          '    install, i  Install new dependencies, or dependencies saved in your',
          '                package.json'
        ].join('\n');

        var result = utils.formatTable(table, {alignRight: [], wrap: [1]});

        expect(result).to.equal(expected);
      });

      it('should format a table with 3 columns, and wrap the 2nd column (options)', function () {
        var table = [
          ['--help', 'Display help & usage information', ''],
          ['--transform, -t', 'Plugin to use when compiling your javascript blah blah blah', '[string]'],
          ['--version, -v', 'Display version number', '']
        ];

        var expected = [
          '    --help           Display help & usage information',
          '    --transform, -t  Plugin to use when compiling your javascript blah  [string]',
          '                     blah blah',
          '    --version, -v    Display version number'
        ].join('\n');

        var result = utils.formatTable(table, {alignRight: [2], wrap: [1]});

        expect(result).to.equal(expected);
      });

      it('should format a table with 3 columns, and wrap the last 2, and right align the final column', function () {
        var table = [
          [
            'line1',
            'Some text that should be wrapped',
            'Some right aligned text that will be wrappped'
          ],
          [
            'line2, l2',
            'Some incidentally wrapped text',
            'Some right aligned text'
          ],
          [
            'line3, l3',
            'No wrap',
            'Right aligned'
          ],
          [
            'line4, l4',
            'Another line of text that should be wrapped',
            'Some more right aligned text that will be wrapped onto 3 different lines because it\'s really quite long'
          ],
          [
            'line5, l5',
            'Ahyphenatedwordwillbewrapped',
            'Anotherhyphenatedwordwillbewrappedbuthastobelongerbecausethiscolumniswider'
          ]
        ];

        var expected = [
          '    line1      Some text that               Some right aligned text that will be',
          '               should be wrapped                                        wrappped',
          '    line2, l2  Some incidentally                         Some right aligned text',
          '               wrapped text',
          '    line3, l3  No wrap                                             Right aligned',
          '    line4, l4  Another line of         Some more right aligned text that will be',
          '               text that should be   wrapped onto 3 different lines because it\'s',
          '               wrapped                                         really quite long',
          '    line5, l5  Ahyphenatedwordwil-  Anotherhyphenatedwordwillbewrappedbuthastob-',
          '               lbewrapped                        elongerbecausethiscolumniswider'
        ].join('\n');

        var result = utils.formatTable(table, {alignRight: [2], wrap: [1, 2]});

        expect(result).to.equal(expected);
      });

      it('should format a table with 3 columns and wrap them all', function () {
        var table = [
          [
            '40 character string la da da da da... da',
            'Another 40 character string la da da doo',
            'A super long 80 character string that will still be wrapped equal to the others!'
          ]
        ];

        // 80 - 4 - 2 - 2 = 72
        // 72 / 4 = 18
        // Column 1 & 2 get 18 chars, and column 3 gets 36

        var expected = [
          '    40 character        Another 40          A super long 80 character string',
          '    string la da da da  character string    that will still be wrapped equal to',
          '    da... da            la da da doo        the others!'
        ].join('\n');

        var result = utils.formatTable(table, {alignRight: [], wrap: [0, 1, 2]});

        expect(result).to.equal(expected);
      });

    });

  });

})();
<|endoftext|>


<commit_before>/**
 * @todo "width" and "height" as parameter
 */
describe('Zoom widget', function () {

	var zoomedImg = 'http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png',
		zoom1 = $('#zoom1').zoom(),
		zoom2 = $('#zoom2').zoom({
			'classes': 'test'
		});

	it('should be defined', function () {
		expect(ch.util.hasOwn(ch, 'Zoom')).toBeTruthy();
		expect(typeof ch.Zoom).toEqual('function');
	});

	describe('should have the following public properties:', function () {

		it('.element', function () {
			expect(ch.util.hasOwn(zoom1, 'element')).toBeTruthy();
			expect(zoom1.element.nodeType).toEqual(1);
		});

		it('.type / .name', function () {
			expect(ch.util.hasOwn(zoom1, 'type')).toBeTruthy();
			expect(typeof zoom1.type).toEqual('string');
			expect(zoom1.type).toEqual('zoom');
		});

		/*it('.constructor', function () {
			expect(ch.util.hasOwn(tooltip, 'constructor')).toBeTruthy();
			expect(typeof tooltip.constructor).toEqual('function');
		});*/

		it('.uid', function () {
			expect(typeof zoom1.uid).toEqual('number');
		});

		it('.content', function () {
			expect(ch.util.hasOwn(zoom1, 'content')).toBeTruthy();
			expect(typeof zoom1.content).toEqual('object');
		});
	});

	describe('should have the following public methods:', function () {

		it('.off()', function () {
			expect(ch.util.hasOwn(zoom1, 'off')).toBeTruthy();
			expect(typeof zoom1.off).toEqual('function');
		});

		it('.on()', function () {
			expect(ch.util.hasOwn(zoom1, 'on')).toBeTruthy();
			expect(typeof zoom1.on).toEqual('function');
		});

		it('.once()', function () {
			expect(ch.util.hasOwn(zoom1, 'once')).toBeTruthy();
			expect(typeof zoom1.once).toEqual('function');
		});

		it('.trigger()', function () {
			expect(ch.util.hasOwn(zoom1, 'trigger')).toBeTruthy();
			expect(typeof zoom1.trigger).toEqual('function');
		});

		it('.closable()', function () {
			expect(ch.util.hasOwn(zoom1, 'closable')).toBeTruthy();
			expect(typeof zoom1.closable).toEqual('function');
		});

		it('.height()', function () {
			expect(ch.util.hasOwn(zoom1, 'height')).toBeTruthy();
			expect(typeof zoom1.height).toEqual('function');
		});

		it('.hide()', function () {
			expect(ch.util.hasOwn(zoom1, 'hide')).toBeTruthy();
			expect(typeof zoom1.hide).toEqual('function');
		});

		it('.isActive()', function () {
			expect(ch.util.hasOwn(zoom1, 'isActive')).toBeTruthy();
			expect(typeof zoom1.isActive).toEqual('function');
		});

		it('.position()', function () {
			expect(ch.util.hasOwn(zoom1, 'position')).toBeTruthy();
			expect(typeof zoom1.position).toEqual('function');
		});

		it('.show()', function () {
			expect(ch.util.hasOwn(zoom1, 'show')).toBeTruthy();
			expect(typeof zoom1.show).toEqual('function');
		});

		it('.width()', function () {
			expect(ch.util.hasOwn(zoom1, 'width')).toBeTruthy();
			expect(typeof zoom1.width).toEqual('function');
		});
	});

	it('trigger should have an "aria-describedby"', function () {
		expect($(zoom1.element).attr('aria-describedby')).toEqual('ch-zoom-1');
	});

	it('trigger should have the "ch-zoom-trigger" classname', function () {
		expect($(zoom1.element).hasClass('ch-zoom-trigger')).toBeTruthy();
	});

	describe('show method', function () {

		describe('should create an element at the bottom of body', function () {

			var $content;

			beforeEach(function () {
				$content = $(document.body).children().last();
			});

			it('with the same ID than the "describedby" ARIA attribute', function () {

				var flag;

				runs(function () {
					flag = false;
					setTimeout(function () { flag = true; }, 500);
				});

				waitsFor(function () { return flag; });

				runs(function () {
					zoom1.show();
					expect($(document.body).children().last().attr('id')).toEqual('ch-zoom-1');
				});

			    expect($content.attr('id')).not.toEqual('ch-zoom-1');
			});

			it('with the ARIA role "tooltip"', function () {
				expect($content.attr('role')).toEqual('tooltip');
			});

			describe('with the following classnames:', function () {

				it('.ch-zoom', function () {
					expect($content.hasClass('ch-zoom')).toBeTruthy();
				});

				it('.ch-points-ltrt', function () {
					expect($content.hasClass('ch-points-ltrt')).toBeTruthy();
				});
			});

			describe('with a child as container of the widget content', function () {

				var text = 'This is a default tooltip',
					$child;

				beforeEach(function () {
					$child = $content.children(':last');
				});

				it('with the "ch-zoom-content" classname', function () {
					expect($child.hasClass('ch-zoom-content')).toBeTruthy();
				});

				it('with an image tag referencing to the zoomed image (same as anchor href)', function () {

					var img = $child.children()[0];

					expect(img.nodeType).toEqual(1);
					expect(img.tagName).toEqual('IMG');
					expect(img.src).toEqual(zoomedImg);
				});
			});
		});

		describe('Public instance', function () {

			it('Should return the same instance than initialized widget', function () {
				expect(zoom1.show()).toEqual(zoom1);
			});
		});
	});

	describe('Hide method', function () {

		it('Should delete the element at the bottom of body.', function () {

			var flag = false;

			expect($(document.body).children().last().attr('id')).toEqual('ch-zoom-1');

			zoom1.hide();

			waits(500);

			runs(function () {
				expect($(document.body).children().last().attr('id')).not.toEqual('ch-modal-1');
			});
		});

		describe('Public instance', function () {

			it('Should return the same instance than initialized widget', function () {
				expect(zoom1.hide()).toEqual(zoom1);
			});
		});
	});

	describe('Position method', function () {

	});

	describe('isActive method', function () {

		it('Should return "true" when the widget is shown', function () {

			zoom1.hide();

			expect(typeof zoom1.isActive()).toEqual('boolean');
			expect(zoom1.isActive()).not.toBeTruthy();
		});

		it('Should return "false" when the widget is hiden', function () {

			zoom1.show();

			expect(typeof zoom1.isActive()).toEqual('boolean');
			expect(zoom1.isActive()).toBeTruthy();
		});
	});

	describe('Width method', function () {

		var $content;

		beforeEach(function () {
			zoom1.show();

			$content = $(document.body).children().last();
		});

		it('As a getter', function () {
			expect(zoom1.width()).toEqual($content.width());
		});

		it('As a setter', function () {

			var finalWidth = 123;

			expect(zoom1.width()).not.toEqual(finalWidth);

			zoom1.width(finalWidth);

			expect(zoom1.width(finalWidth)).toEqual(zoom1);

			expect(zoom1.width()).toEqual(finalWidth);
		});
	});

	describe('Height method', function () {

		var $content;

		beforeEach(function () {
			zoom1.show();

			$content = $(document.body).children().last();
		});

		it('As a getter', function () {
			expect(zoom1.height()).toEqual($content.height());
		});

		it('As a setter', function () {

			var finalHeight = 55;

			expect(zoom1.height()).not.toEqual(finalHeight);

			zoom1.height(finalHeight);

			expect(zoom1.height(finalHeight)).toEqual(zoom1);

			expect(zoom1.height()).toEqual(finalHeight);
		});
	});

	describe('An instance configured with custom classnames', function () {

		it('should contain the specified classname in its container element', function () {

			zoom2.show();

			var $container = $(document.body).children().last();

			expect($container.hasClass('ch-box')).toBeFalsy();
			expect($container.hasClass('test')).toBeTruthy();
		});
	});

	describe('Position method', function () {

		describe('as a getter should return the current "position" configuration', function () {

			var result = zoom1.position();

			it('as an object', function () {
				expect(typeof result).toEqual('object');
			});

			describe('with the following public properties:', function () {

				it('context should be the trigger', function () {
					expect(ch.util.hasOwn(result, 'context')).toBeTruthy();
					// Exists in DOM
					expect(result.context[0].id).toEqual('zoom1');
				});

				it('element', function () {
					expect(ch.util.hasOwn(result, 'element')).toBeTruthy();
					// Exists in DOM
					expect(result.element[0].nodeType).toEqual(1);
				});

				it('offset', function () {
					expect(ch.util.hasOwn(result, 'offset')).toBeTruthy();
					expect(typeof result.offset).toEqual('string');
					expect(result.offset).toEqual('20 0');
				});

				it('points', function () {
					expect(ch.util.hasOwn(result, 'points')).toBeTruthy();
					expect(typeof result.points).toEqual('string');
					expect(result.points).toEqual('lt rt');
				});

				it('reposition', function () {
					expect(ch.util.hasOwn(result, 'reposition')).toBeTruthy();
					expect(typeof result.reposition).toEqual('boolean');
					expect(result.reposition).toBeFalsy();
				});
			});
		});

		describe('as a setter should replace the following properties:', function () {

			it('context', function () {

				var newID = 'zoom1';

				expect(zoom2.position().context[0].id).not.toEqual(newID);

				zoom2.position({
					'context': $('#zoom1')
				});

				expect(zoom2.position().context[0].id).toEqual(newID);
			});

			it('offset', function () {

				var newOffset = '12 34';

				expect(zoom1.position().offset).not.toEqual(newOffset);

				zoom1.position({
					'offset': newOffset
				});

				expect(zoom1.position().offset).toEqual(newOffset);
			});

			it('points', function () {

				var newPoints = 'cb cb';

				expect(zoom1.position().points).not.toEqual(newPoints);

				zoom1.position({
					'points': newPoints
				});

				expect(zoom1.position().points).toEqual(newPoints);
			});

			it('reposition', function () {

				var newReposition = false;

				expect(zoom1.position().reposition).not.toEqual(newReposition);

				zoom1.position({
					'reposition': newReposition
				});

				expect(zoom1.position().reposition).toEqual(newReposition);
			});
		});
	});
});<commit_msg>change the content test<commit_after>/**
 * @todo "width" and "height" as parameter
 */
describe('Zoom widget', function () {

	var zoomedImg = 'http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png',
		zoom1 = $('#zoom1').zoom(),
		zoom2 = $('#zoom2').zoom({
			'classes': 'test'
		});

	it('should be defined', function () {
		expect(ch.util.hasOwn(ch, 'Zoom')).toBeTruthy();
		expect(typeof ch.Zoom).toEqual('function');
	});

	describe('should have the following public properties:', function () {

		it('.element', function () {
			expect(ch.util.hasOwn(zoom1, 'element')).toBeTruthy();
			expect(zoom1.element.nodeType).toEqual(1);
		});

		it('.type / .name', function () {
			expect(ch.util.hasOwn(zoom1, 'type')).toBeTruthy();
			expect(typeof zoom1.type).toEqual('string');
			expect(zoom1.type).toEqual('zoom');
		});

		/*it('.constructor', function () {
			expect(ch.util.hasOwn(tooltip, 'constructor')).toBeTruthy();
			expect(typeof tooltip.constructor).toEqual('function');
		});*/

		it('.uid', function () {
			expect(typeof zoom1.uid).toEqual('number');
		});

		it('.content', function () {
			expect(ch.util.hasOwn(zoom1, 'content')).toBeTruthy();
			expect(typeof zoom1.content).toEqual('function');
		});
	});

	describe('should have the following public methods:', function () {

		it('.off()', function () {
			expect(ch.util.hasOwn(zoom1, 'off')).toBeTruthy();
			expect(typeof zoom1.off).toEqual('function');
		});

		it('.on()', function () {
			expect(ch.util.hasOwn(zoom1, 'on')).toBeTruthy();
			expect(typeof zoom1.on).toEqual('function');
		});

		it('.once()', function () {
			expect(ch.util.hasOwn(zoom1, 'once')).toBeTruthy();
			expect(typeof zoom1.once).toEqual('function');
		});

		it('.trigger()', function () {
			expect(ch.util.hasOwn(zoom1, 'trigger')).toBeTruthy();
			expect(typeof zoom1.trigger).toEqual('function');
		});

		it('.closable()', function () {
			expect(ch.util.hasOwn(zoom1, 'closable')).toBeTruthy();
			expect(typeof zoom1.closable).toEqual('function');
		});

		it('.height()', function () {
			expect(ch.util.hasOwn(zoom1, 'height')).toBeTruthy();
			expect(typeof zoom1.height).toEqual('function');
		});

		it('.hide()', function () {
			expect(ch.util.hasOwn(zoom1, 'hide')).toBeTruthy();
			expect(typeof zoom1.hide).toEqual('function');
		});

		it('.isActive()', function () {
			expect(ch.util.hasOwn(zoom1, 'isActive')).toBeTruthy();
			expect(typeof zoom1.isActive).toEqual('function');
		});

		it('.position()', function () {
			expect(ch.util.hasOwn(zoom1, 'position')).toBeTruthy();
			expect(typeof zoom1.position).toEqual('function');
		});

		it('.show()', function () {
			expect(ch.util.hasOwn(zoom1, 'show')).toBeTruthy();
			expect(typeof zoom1.show).toEqual('function');
		});

		it('.width()', function () {
			expect(ch.util.hasOwn(zoom1, 'width')).toBeTruthy();
			expect(typeof zoom1.width).toEqual('function');
		});
	});

	it('trigger should have an "aria-describedby"', function () {
		expect($(zoom1.element).attr('aria-describedby')).toEqual('ch-zoom-1');
	});

	it('trigger should have the "ch-zoom-trigger" classname', function () {
		expect($(zoom1.element).hasClass('ch-zoom-trigger')).toBeTruthy();
	});

	describe('show method', function () {

		describe('should create an element at the bottom of body', function () {

			var $content;

			beforeEach(function () {
				$content = $(document.body).children().last();
			});

			it('with the same ID than the "describedby" ARIA attribute', function () {

				var flag;

				runs(function () {
					flag = false;
					setTimeout(function () { flag = true; }, 500);
				});

				waitsFor(function () { return flag; });

				runs(function () {
					zoom1.show();
					expect($(document.body).children().last().attr('id')).toEqual('ch-zoom-1');
				});

			    expect($content.attr('id')).not.toEqual('ch-zoom-1');
			});

			it('with the ARIA role "tooltip"', function () {
				expect($content.attr('role')).toEqual('tooltip');
			});

			describe('with the following classnames:', function () {

				it('.ch-zoom', function () {
					expect($content.hasClass('ch-zoom')).toBeTruthy();
				});

				it('.ch-points-ltrt', function () {
					expect($content.hasClass('ch-points-ltrt')).toBeTruthy();
				});
			});

			describe('with a child as container of the widget content', function () {

				var text = 'This is a default tooltip',
					$child;

				beforeEach(function () {
					$child = $content.children(':last');
				});

				it('with the "ch-zoom-content" classname', function () {
					expect($child.hasClass('ch-zoom-content')).toBeTruthy();
				});

				it('with an image tag referencing to the zoomed image (same as anchor href)', function () {

					var img = $child.children()[0];

					expect(img.nodeType).toEqual(1);
					expect(img.tagName).toEqual('IMG');
					expect(img.src).toEqual(zoomedImg);
				});
			});
		});

		describe('Public instance', function () {

			it('Should return the same instance than initialized widget', function () {
				expect(zoom1.show()).toEqual(zoom1);
			});
		});
	});

	describe('Hide method', function () {

		it('Should delete the element at the bottom of body.', function () {

			var flag = false;

			expect($(document.body).children().last().attr('id')).toEqual('ch-zoom-1');

			zoom1.hide();

			waits(500);

			runs(function () {
				expect($(document.body).children().last().attr('id')).not.toEqual('ch-modal-1');
			});
		});

		describe('Public instance', function () {

			it('Should return the same instance than initialized widget', function () {
				expect(zoom1.hide()).toEqual(zoom1);
			});
		});
	});

	describe('Position method', function () {

	});

	describe('isActive method', function () {

		it('Should return "true" when the widget is shown', function () {

			zoom1.hide();

			expect(typeof zoom1.isActive()).toEqual('boolean');
			expect(zoom1.isActive()).not.toBeTruthy();
		});

		it('Should return "false" when the widget is hiden', function () {

			zoom1.show();

			expect(typeof zoom1.isActive()).toEqual('boolean');
			expect(zoom1.isActive()).toBeTruthy();
		});
	});

	describe('Width method', function () {

		var $content;

		beforeEach(function () {
			zoom1.show();

			$content = $(document.body).children().last();
		});

		it('As a getter', function () {
			expect(zoom1.width()).toEqual($content.width());
		});

		it('As a setter', function () {

			var finalWidth = 123;

			expect(zoom1.width()).not.toEqual(finalWidth);

			zoom1.width(finalWidth);

			expect(zoom1.width(finalWidth)).toEqual(zoom1);

			expect(zoom1.width()).toEqual(finalWidth);
		});
	});

	describe('Height method', function () {

		var $content;

		beforeEach(function () {
			zoom1.show();

			$content = $(document.body).children().last();
		});

		it('As a getter', function () {
			expect(zoom1.height()).toEqual($content.height());
		});

		it('As a setter', function () {

			var finalHeight = 55;

			expect(zoom1.height()).not.toEqual(finalHeight);

			zoom1.height(finalHeight);

			expect(zoom1.height(finalHeight)).toEqual(zoom1);

			expect(zoom1.height()).toEqual(finalHeight);
		});
	});

	describe('An instance configured with custom classnames', function () {

		it('should contain the specified classname in its container element', function () {

			zoom2.show();

			var $container = $(document.body).children().last();

			expect($container.hasClass('ch-box')).toBeFalsy();
			expect($container.hasClass('test')).toBeTruthy();
		});
	});

	describe('Position method', function () {

		describe('as a getter should return the current "position" configuration', function () {

			var result = zoom1.position();

			it('as an object', function () {
				expect(typeof result).toEqual('object');
			});

			describe('with the following public properties:', function () {

				it('context should be the trigger', function () {
					expect(ch.util.hasOwn(result, 'context')).toBeTruthy();
					// Exists in DOM
					expect(result.context[0].id).toEqual('zoom1');
				});

				it('element', function () {
					expect(ch.util.hasOwn(result, 'element')).toBeTruthy();
					// Exists in DOM
					expect(result.element[0].nodeType).toEqual(1);
				});

				it('offset', function () {
					expect(ch.util.hasOwn(result, 'offset')).toBeTruthy();
					expect(typeof result.offset).toEqual('string');
					expect(result.offset).toEqual('20 0');
				});

				it('points', function () {
					expect(ch.util.hasOwn(result, 'points')).toBeTruthy();
					expect(typeof result.points).toEqual('string');
					expect(result.points).toEqual('lt rt');
				});

				it('reposition', function () {
					expect(ch.util.hasOwn(result, 'reposition')).toBeTruthy();
					expect(typeof result.reposition).toEqual('boolean');
					expect(result.reposition).toBeFalsy();
				});
			});
		});

		describe('as a setter should replace the following properties:', function () {

			it('context', function () {

				var newID = 'zoom1';

				expect(zoom2.position().context[0].id).not.toEqual(newID);

				zoom2.position({
					'context': $('#zoom1')
				});

				expect(zoom2.position().context[0].id).toEqual(newID);
			});

			it('offset', function () {

				var newOffset = '12 34';

				expect(zoom1.position().offset).not.toEqual(newOffset);

				zoom1.position({
					'offset': newOffset
				});

				expect(zoom1.position().offset).toEqual(newOffset);
			});

			it('points', function () {

				var newPoints = 'cb cb';

				expect(zoom1.position().points).not.toEqual(newPoints);

				zoom1.position({
					'points': newPoints
				});

				expect(zoom1.position().points).toEqual(newPoints);
			});

			it('reposition', function () {

				var newReposition = 'test';

				expect(zoom1.position().reposition).not.toEqual(newReposition);

				zoom1.position({
					'reposition': newReposition
				});

				expect(zoom1.position().reposition).toEqual('test');
			});
		});
	});
});<|endoftext|>


<commit_before>var BaseAnalysisFormModel = require('../base-analysis-form-model.js');
var _ = require('underscore');
var distanceOnMeters = function (type) {
  switch (type) {
    case 'kilometers': return 1000;
    case 'miles': return 1609.34;
    default: return 1;
  }
};

var ANALYSES_MAP = {
  buffer: {
    getAttrs: function () {
      return ['distance', 'radio'];
    },
    getAnalysisAttrs: function () {
      return {
        distance: this.get('distance'),
        radio: parseFloat(this.get('radio')) * distanceOnMeters(this.get('distance'))
      };
    },
    getSchema: function () {
      return {
        source: {
          type: 'Select',
          text: _t('editor.layers.analysis-form.source'),
          options: [ this.get('source') ],
          editorAttrs: { disabled: true }
        },
        type: {
          type: 'Radio',
          text: _t('editor.layers.analysis-form.type'),
          options: [
            {
              val: 'buffer',
              label: _t('editor.layers.analysis-form.distance')
            }, {
              val: 'trade-area',
              label: _t('editor.layers.analysis-form.time')
            }
          ]
        },
        distance: {
          type: 'Radio',
          text: _t('editor.layers.analysis-form.distance'),
          options: [
            {
              val: 'meters',
              label: _t('editor.layers.analysis-form.meters')
            }, {
              val: 'kilometers',
              label: _t('editor.layers.analysis-form.kilometers')
            }, {
              val: 'miles',
              label: _t('editor.layers.analysis-form.miles')
            }
          ]
        },
        radio: {
          type: 'Number',
          label: _t('editor.layers.analysis-form.radio'),
          validators: ['required']
        }
      };
    },
    getDefaults: function () {
      return {
        type: 'buffer',
        distance: 'meters',
        radio: 100
      };
    }
  },
  'trade-area': {
    getAttrs: function () {
      return ['kind', 'time'];
    },
    getAnalysisAttrs: function () {
      return {
        kind: this.get('kind'),
        time: this.get('time')
      };
    },
    getSchema: function () {
      return {
        source: {
          type: 'Select',
          label: _t('editor.layers.analysis-form.source'),
          options: [ this.get('source') ],
          editorAttrs: { disabled: true }
        },
        type: {
          type: 'Radio',
          text: _t('editor.layers.analysis-form.type'),
          options: [
            {
              val: 'buffer',
              label: _t('editor.layers.analysis-form.distance')
            }, {
              val: 'trade-area',
              label: _t('editor.layers.analysis-form.time')
            }
          ]
        },
        kind: {
          type: 'Select',
          title: _t('editor.layers.analysis-form.by'),
          options: [
            {
              val: 'walk',
              label: _t('editor.layers.analysis-form.by-walk')
            }, {
              val: 'drive',
              label: _t('editor.layers.analysis-form.by-car')
            }, {
              val: 'bike',
              label: _t('editor.layers.analysis-form.by-bike')
            }
          ]
        },
        time: {
          type: 'Number',
          text: _t('editor.layers.analysis-form.time'),
          validators: ['required']
        }
      };
    },
    getDefaults: function () {
      return {
        type: 'trade-area',
        kind: 'walk',
        time: 100
      };
    }
  }
};

module.exports = BaseAnalysisFormModel.extend({

  initialize: function (attrs, opts) {
    if (!opts.analysisDefinitionNodeModel) throw new Error('analysisDefinitionNodeModel is required');
    this._analysisDefinitionNodeModel = opts.analysisDefinitionNodeModel;
    this._setDefaults();
    this._adjustRadioDistance();
    this._setModel();
  },

  _setDefaults: function () {
    var analysisType = this.get('type');
    var defaultAttrs = ANALYSES_MAP[analysisType].getDefaults.bind(this)();
    this.set(_.extend(defaultAttrs, this.attributes));
  },

  _adjustRadioDistance: function () {
    if (this.get('type') === 'buffer') {
      this.set({
        radio: parseFloat(this.get('radio')) / distanceOnMeters(this.get('distance'))
      }, { silent: true });
    }
  },

  _setModel: function (applyDefaults) {
    var analysisType = this.get('type');
    this._setDefaults();
    this._updateAnalysisNode();
    this.schema = ANALYSES_MAP[analysisType].getSchema.bind(this)();
    this.bind('change', _.debounce(this._onChange.bind(this), 500));
  },

  _unsetModel: function () {
    var previousType = this.previous('type');
    var oldAttrs = ANALYSES_MAP[previousType].getAttrs.bind(this)();

    _.each(oldAttrs, function (attr) {
      this.unset(attr, { silent: true });
      this._analysisDefinitionNodeModel.unset(attr, { silent: true });
    }, this);

    this.unbind(null, null, this);
  },

  _onChangeType: function (newType) {
    this._unsetModel();
    this._analysisDefinitionNodeModel.set('type', newType, { silent: true });
    this._setModel();
    this.trigger('changeSchema', this);
  },

  _onChange: function () {
    if (this.changed.type) {
      this._onChangeType(this.changed.type);
    } else {
      this._updateAnalysisNode();
    }
  },

  _updateAnalysisNode: function () {
    var analysisType = this.get('type');
    this._analysisDefinitionNodeModel.set(ANALYSES_MAP[analysisType].getAnalysisAttrs.bind(this)());
  }

});
<commit_msg>Changed name of the method and checking if type is buffer before<commit_after>var BaseAnalysisFormModel = require('../base-analysis-form-model.js');
var _ = require('underscore');
var distanceOnMeters = function (type) {
  switch (type) {
    case 'kilometers': return 1000;
    case 'miles': return 1609.34;
    default: return 1;
  }
};

var ANALYSES_MAP = {
  buffer: {
    getAttrs: function () {
      return ['distance', 'radio'];
    },
    getAnalysisAttrs: function () {
      return {
        distance: this.get('distance'),
        radio: parseFloat(this.get('radio')) * distanceOnMeters(this.get('distance'))
      };
    },
    getSchema: function () {
      return {
        source: {
          type: 'Select',
          text: _t('editor.layers.analysis-form.source'),
          options: [ this.get('source') ],
          editorAttrs: { disabled: true }
        },
        type: {
          type: 'Radio',
          text: _t('editor.layers.analysis-form.type'),
          options: [
            {
              val: 'buffer',
              label: _t('editor.layers.analysis-form.distance')
            }, {
              val: 'trade-area',
              label: _t('editor.layers.analysis-form.time')
            }
          ]
        },
        distance: {
          type: 'Radio',
          text: _t('editor.layers.analysis-form.distance'),
          options: [
            {
              val: 'meters',
              label: _t('editor.layers.analysis-form.meters')
            }, {
              val: 'kilometers',
              label: _t('editor.layers.analysis-form.kilometers')
            }, {
              val: 'miles',
              label: _t('editor.layers.analysis-form.miles')
            }
          ]
        },
        radio: {
          type: 'Number',
          label: _t('editor.layers.analysis-form.radio'),
          validators: ['required']
        }
      };
    },
    getDefaults: function () {
      return {
        type: 'buffer',
        distance: 'meters',
        radio: 100
      };
    }
  },
  'trade-area': {
    getAttrs: function () {
      return ['kind', 'time'];
    },
    getAnalysisAttrs: function () {
      return {
        kind: this.get('kind'),
        time: this.get('time')
      };
    },
    getSchema: function () {
      return {
        source: {
          type: 'Select',
          label: _t('editor.layers.analysis-form.source'),
          options: [ this.get('source') ],
          editorAttrs: { disabled: true }
        },
        type: {
          type: 'Radio',
          text: _t('editor.layers.analysis-form.type'),
          options: [
            {
              val: 'buffer',
              label: _t('editor.layers.analysis-form.distance')
            }, {
              val: 'trade-area',
              label: _t('editor.layers.analysis-form.time')
            }
          ]
        },
        kind: {
          type: 'Select',
          title: _t('editor.layers.analysis-form.by'),
          options: [
            {
              val: 'walk',
              label: _t('editor.layers.analysis-form.by-walk')
            }, {
              val: 'drive',
              label: _t('editor.layers.analysis-form.by-car')
            }, {
              val: 'bike',
              label: _t('editor.layers.analysis-form.by-bike')
            }
          ]
        },
        time: {
          type: 'Number',
          text: _t('editor.layers.analysis-form.time'),
          validators: ['required']
        }
      };
    },
    getDefaults: function () {
      return {
        type: 'trade-area',
        kind: 'walk',
        time: 100
      };
    }
  }
};

module.exports = BaseAnalysisFormModel.extend({

  initialize: function (attrs, opts) {
    if (!opts.analysisDefinitionNodeModel) throw new Error('analysisDefinitionNodeModel is required');
    this._analysisDefinitionNodeModel = opts.analysisDefinitionNodeModel;
    this._setDefaults();
    if (this.get('type') === 'buffer') {
      this._adjustRadioDistance();
    }
    this._setModel();
  },

  _setDefaults: function () {
    var analysisType = this.get('type');
    var defaultAttrs = ANALYSES_MAP[analysisType].getDefaults.bind(this)();
    this.set(_.extend(defaultAttrs, this.attributes));
  },

  _adjustRadioDistance: function () {
    this.set({
      radio: parseFloat(this.get('radio')) / distanceOnMeters(this.get('distance'))
    }, { silent: true });
  },

  _setModel: function (applyDefaults) {
    var analysisType = this.get('type');
    this._setDefaults();
    this._updateAnalysisNode();
    this.schema = ANALYSES_MAP[analysisType].getSchema.bind(this)();
    this.bind('change', _.debounce(this._onChange.bind(this), 500));
  },

  _unsetModel: function () {
    var previousType = this.previous('type');
    var oldAttrs = ANALYSES_MAP[previousType].getAttrs.bind(this)();

    _.each(oldAttrs, function (attr) {
      this.unset(attr, { silent: true });
      this._analysisDefinitionNodeModel.unset(attr, { silent: true });
    }, this);

    this.unbind(null, null, this);
  },

  _onChangeType: function (newType) {
    this._unsetModel();
    this._analysisDefinitionNodeModel.set('type', newType, { silent: true });
    this._setModel();
    this.trigger('changeSchema', this);
  },

  _onChange: function () {
    if (this.changed.type) {
      this._onChangeType(this.changed.type);
    } else {
      this._updateAnalysisNode();
    }
  },

  _updateAnalysisNode: function () {
    var analysisType = this.get('type');
    this._analysisDefinitionNodeModel.set(ANALYSES_MAP[analysisType].getAnalysisAttrs.bind(this)());
  }

});
<|endoftext|>