<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.
 */
 ({
	 browsers: ["-IE7","-IE8"],
	 colIds: ["id", "name", "grade"],

	 /**
	  * Test basic flow:
      *  - triggering an edit moves focus into an inputElement
      *  - changing the value in the input element triggers an onEdit event
	  */
	 testEditTrigger : {
		test : [function(cmp) {
			this.triggerEditOnCell(cmp, 0, 2);
		}, function(cmp) {
			$A.test.addWaitForWithFailureMessage(true, function() {
				var activeElement = $A.test.getActiveElement();
				return activeElement.tagName === 'INPUT';
			}, "Input element should be focused.");
		}, function(cmp) {
		    // Trigger submit on the edit panel with new value
		    var input = cmp.find("grid")._panelBody.get("v.inputComponent")[0];
		    input.set("v.value", 5);
		    input.getEvent("keydown").setParams({
		        keyCode : 13,
		        domEvent : {
		            type : "keydown",
		            preventDefault : function() {}
		        }
		    }).fire();
		}, function(cmp) {
		    $A.test.addWaitForWithFailureMessage(5, function() {
		        var lastEdited = cmp.get("v.lastEdited");
		        return lastEdited && lastEdited.value;
		    }, "The lastEdited attribute should be updated with the last edited value");
		}]
	 },

	 /**
	  * Test append functionality
	  */
	 testAppendItems : {
		 test : function(cmp) {
			 this.triggerAppend(cmp);
			 this.waitForRows(11);
		 }
	 },

	 /**
	  * Test editing multiple cells opens and closes appropriate panel for cell.
	  */
	 testEditPanelForMulitpleCells : {
		 test : [function(cmp) {
			 this.triggerEditOnCell(cmp, 0, 2);
		 }, function(cmp) {
			 this.waitForPanelOpen(cmp);
		 }, function(cmp) {
			 this.verifyPanelContent(cmp, 0);
			 this.triggerEditOnCell(cmp, 6, 0);
		 }, function(cmp) {
			 this.waitForPanelContent(cmp, 6);
		 }]
	 },

	 /**
	  * Test edit cell with empty value to a cell with value.
	  */
	 testEditEmptyCell : {
		 test : [function(cmp) {
			 this.triggerEditOnCell(cmp, 5, 1);
		 }, function(cmp) {
			 this.waitForPanelOpen(cmp);
		 }, function(cmp) {
			 this.verifyPanelContent(cmp, '');
			 this.editPanel(cmp, 'something new');
		 }, function(cmp) {
			 this.waitForCellContent(cmp, 5, 1, 'something new');
		 }]
	 },

	 triggerEditOnCell : function(cmp, rowIndex, colIndex) {
		 var tbody = document.getElementsByTagName("tbody")[0];
		 var trs = this.getOnlyTrs(tbody.children);
		 var trigger = trs[rowIndex].children[colIndex].querySelector('.triggerContainer button');

		 $A.test.clickOrTouch(trigger);
	 },

	 getOnlyTrs : function(elements) {
		 var elementArray = [];

		 for (var i = 0; i < elements.length; i++) {
			 if (elements[i].tagName == 'TR') {
				 elementArray.push(elements[i]);
			 }
		 }
		 return elementArray;
	 },

	 waitForRows : function(rowCount) {
		 var that = this;
		 $A.test.addWaitForWithFailureMessage(rowCount, function() {
			 var tbody = document.getElementsByTagName("tbody")[0];
			 var trs = that.getOnlyTrs(tbody.children);
			 return trs.length;
		 }, "Number of rows expected is incorrect.");
	 },

	 triggerAppend : function(cmp) {
		 cmp.find("appendButton").get("e.press").fire();
	 },

	 getPanelFromDomElement : function(cmp, panelIndex) {
		 panelIndex = panelIndex ? panelIndex : 0;
		 var panels = $A.test.getElementByClass('editPanel');
		 if (0 < panelIndex > panels.length) {
			 return undefined;
		 }
		 var panel = panels[panelIndex];
		 var htmlCmp = $A.componentService.getRenderingComponentForElement(panel);
		 return htmlCmp.getAttributeValueProvider();
	 },

	 waitForPanelOpen : function(cmp) {
		 this.waitForPanel(cmp, true);
	 },

	 waitForPanelClose : function(cmp) {
		 this.waitForPanel(cmp, false);
	 },

	 waitForPanel : function(cmp, isOpen) {
		 $A.test.addWaitForWithFailureMessage(isOpen, function() {
			 var panel = $A.test.getElementByClass('editPanel');
			 return !$A.util.isUndefinedOrNull(panel);
		 }, 'Edit panel for cell is supposed to be open="' + isOpen + '" but was not');
	 },

	 getPanelContent : function(cmp, panelIndex) {
		 panelIndex = panelIndex ? panelIndex : 0;
		 var panel = this.getPanelFromDomElement(cmp, panelIndex);
		 if (!$A.util.isUndefinedOrNull(panel)) {
			 return panel.get('v.inputComponent')[0].get('v.value');
		 }
		 return undefined;
	 },

	 verifyPanelContent : function(cmp, expected, panelIndex) {
		 panelIndex = panelIndex ? panelIndex : 0;
		 var actual = this.getPanelContent(cmp, panelIndex);
		 $A.test.assertEquals(expected, actual, 'Panel content did not match.');
	 },

	 waitForPanelContent : function(cmp, expected, panelIndex) {
		 panelIndex = panelIndex ? panelIndex : 0;
		 var that = this;
		 var actual = '';
		 $A.test.addWaitForWithFailureMessage(expected, function() {
			 actual = that.getPanelContent(cmp, panelIndex);
			 if (actual) {
				 return actual;
			 } else {
				 // There is a test flapping issue where 2 panels are open at the same time.
				 // Probably test running too fast? Manually it does not happen. Hack is to
				 // add a second check to look for content in other panel.
				 var newPanelIndex = panelIndex == 0 ? panelIndex+1 : panelIndex-1;
				 actual = that.getPanelContent(cmp, newPanelIndex);
				 if (actual) {
					 return actual;
				 }
			 }
			 return  'Testing Error: Could not read panel content';
		 }, 'Expected text in edit panel for cell is supposed to be "' + expected + '" but was "' + actual + '"');
	 },

	 editPanel : function(cmp, newInput, panelIndex) {
		 panelIndex = panelIndex ? panelIndex : 0;
		 var panel = this.getPanelFromDomElement(cmp, panelIndex);
		 if (!$A.util.isUndefinedOrNull(panel)) {
			 var input = panel.get('v.inputComponent')[0];
			 input.set('v.value', newInput);
			 this.commitCellContent(panel);
		 }
	 },

	 commitCellContent : function(cmp) {
         cmp.getEvent('submit').setParams({
             payload : {
                 index : cmp.get('v.index'),
                 key : cmp.get('v.key'),
                 value : cmp.get('v.inputComponent')[0].get('v.value')
             }
         }).fire();
     },

	 clickOutOfEditPanel : function(cmp) {
		 var input = cmp.find('inputTxt').getElement();
		 $A.test.clickOrTouch(input);
	 },

	 getCellElem : function(cmp, rowIndex, colIndex) {
		 var tbody = document.getElementsByTagName('tbody')[0];
		 var rows = this.getOnlyTrs(tbody.children);
		 var col = rows[rowIndex].children[colIndex];
		 return col;
	 },

	 verifyCellContent : function(cmp, rowIndex, colIndex, expected) {
	     var cell = this.getCellElem(cmp, rowIndex, colIndex);
	     var actual = $A.test.getText(cell);
	     $A.test.assertEquals(expected, actual, 'Cell value is incorrect');
	 },

	 waitForCellContent : function(cmp, rowIndex, colIndex, expected) {
	     var that = this;
	     var actual = '';
	     $A.test.addWaitForWithFailureMessage(expected, function() {
             var cell = that.getCellElem(cmp, rowIndex, colIndex);
             actual = $A.test.getText(cell);
             return actual;
         }, 'Cell value was not updated expecting "' + expected + '" but was "' + actual + '"');
	 }
 })
<commit_msg>Adding attribute validation test to inlineEdit<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.
 */
 ({
	 browsers: ["-IE7","-IE8"],
	 colIds: ["id", "name", "grade"],

	 /**
	  * Test basic flow:
      *  - triggering an edit moves focus into an inputElement
      *  - changing the value in the input element triggers an onEdit event
	  */
	 testEditTrigger : {
		test : [function(cmp) {
			this.triggerEditOnCell(cmp, 0, 2);
		}, function(cmp) {
			$A.test.addWaitForWithFailureMessage(true, function() {
				var activeElement = $A.test.getActiveElement();
				return activeElement.tagName === 'INPUT';
			}, "Input element should be focused.");
		}, function(cmp) {
		    // Trigger submit on the edit panel with new value
		    var input = cmp.find("grid")._panelBody.get("v.inputComponent")[0];
		    input.set("v.value", 5);
		    input.getEvent("keydown").setParams({
		        keyCode : 13,
		        domEvent : {
		            type : "keydown",
		            preventDefault : function() {}
		        }
		    }).fire();
		}, function(cmp) {
		    $A.test.addWaitForWithFailureMessage(5, function() {
		        var lastEdited = cmp.get("v.lastEdited");
		        return lastEdited && lastEdited.value;
		    }, "The lastEdited attribute should be updated with the last edited value");
		}]
	 },

	 /**
	   *  Verifies the attribute value shows up correctly after event fired
	  */
	 testOutputAttribute : {
	     test : [function(cmp) {
	         this.triggerEditOnCell(cmp, 1, 3);
	     }, function(cmp) {
	         $A.test.addWaitForWithFailureMessage(true, function() {
	             var activeElement = $A.test.getActiveElement();
	             return activeElement.tagName === 'INPUT';
	         }, "Input element should be focused.");
	     }, function(cmp) {
	         // Trigger submit on the edit panel with new value
	         var input = cmp.find("grid")._panelBody.get("v.inputComponent")[0];
	         input.set("v.value", "abc");
	         input.getEvent("keydown").setParams({
	             keyCode : 13,
	             domEvent : {
	                 type : "keydown",
	                 preventDefault : function() {}
	             }
	         }).fire();
	     }, function(cmp) {
	         var lastEdited = cmp.get("v.lastEdited");
	         $A.test.assertEquals("abc", lastEdited.value, "Default value of output component is wrong");
	     }]
	 },

	 /**
	  * Test append functionality
	  */
	 testAppendItems : {
		 test : function(cmp) {
			 this.triggerAppend(cmp);
			 this.waitForRows(11);
		 }
	 },

	 /**
	  * Test editing multiple cells opens and closes appropriate panel for cell.
	  */
	 testEditPanelForMulitpleCells : {
		 test : [function(cmp) {
			 this.triggerEditOnCell(cmp, 0, 2);
		 }, function(cmp) {
			 this.waitForPanelOpen(cmp);
		 }, function(cmp) {
			 this.verifyPanelContent(cmp, 0);
			 this.triggerEditOnCell(cmp, 6, 0);
		 }, function(cmp) {
			 this.waitForPanelContent(cmp, 6);
		 }]
	 },

	 /**
	  * Test edit cell with empty value to a cell with value.
	  */
	 testEditEmptyCell : {
		 test : [function(cmp) {
			 this.triggerEditOnCell(cmp, 5, 1);
		 }, function(cmp) {
			 this.waitForPanelOpen(cmp);
		 }, function(cmp) {
			 this.verifyPanelContent(cmp, '');
			 this.editPanel(cmp, 'something new');
		 }, function(cmp) {
			 this.waitForCellContent(cmp, 5, 1, 'something new');
		 }]
	 },

	 triggerEditOnCell : function(cmp, rowIndex, colIndex) {
		 var tbody = document.getElementsByTagName("tbody")[0];
		 var trs = this.getOnlyTrs(tbody.children);
		 var trigger = trs[rowIndex].children[colIndex].querySelector('.triggerContainer button');

		 $A.test.clickOrTouch(trigger);
	 },

	 getOnlyTrs : function(elements) {
		 var elementArray = [];

		 for (var i = 0; i < elements.length; i++) {
			 if (elements[i].tagName == 'TR') {
				 elementArray.push(elements[i]);
			 }
		 }
		 return elementArray;
	 },

	 waitForRows : function(rowCount) {
		 var that = this;
		 $A.test.addWaitForWithFailureMessage(rowCount, function() {
			 var tbody = document.getElementsByTagName("tbody")[0];
			 var trs = that.getOnlyTrs(tbody.children);
			 return trs.length;
		 }, "Number of rows expected is incorrect.");
	 },

	 triggerAppend : function(cmp) {
		 cmp.find("appendButton").get("e.press").fire();
	 },

	 getPanelFromDomElement : function(cmp, panelIndex) {
		 panelIndex = panelIndex ? panelIndex : 0;
		 var panels = $A.test.getElementByClass('editPanel');
		 if (0 < panelIndex > panels.length) {
			 return undefined;
		 }
		 var panel = panels[panelIndex];
		 var htmlCmp = $A.componentService.getRenderingComponentForElement(panel);
		 return htmlCmp.getAttributeValueProvider();
	 },

	 waitForPanelOpen : function(cmp) {
		 this.waitForPanel(cmp, true);
	 },

	 waitForPanelClose : function(cmp) {
		 this.waitForPanel(cmp, false);
	 },

	 waitForPanel : function(cmp, isOpen) {
		 $A.test.addWaitForWithFailureMessage(isOpen, function() {
			 var panel = $A.test.getElementByClass('editPanel');
			 return !$A.util.isUndefinedOrNull(panel);
		 }, 'Edit panel for cell is supposed to be open="' + isOpen + '" but was not');
	 },

	 getPanelContent : function(cmp, panelIndex) {
		 panelIndex = panelIndex ? panelIndex : 0;
		 var panel = this.getPanelFromDomElement(cmp, panelIndex);
		 if (!$A.util.isUndefinedOrNull(panel)) {
			 return panel.get('v.inputComponent')[0].get('v.value');
		 }
		 return undefined;
	 },

	 verifyPanelContent : function(cmp, expected, panelIndex) {
		 panelIndex = panelIndex ? panelIndex : 0;
		 var actual = this.getPanelContent(cmp, panelIndex);
		 $A.test.assertEquals(expected, actual, 'Panel content did not match.');
	 },

	 waitForPanelContent : function(cmp, expected, panelIndex) {
		 panelIndex = panelIndex ? panelIndex : 0;
		 var that = this;
		 var actual = '';
		 $A.test.addWaitForWithFailureMessage(expected, function() {
			 actual = that.getPanelContent(cmp, panelIndex);
			 if (actual) {
				 return actual;
			 } else {
				 // There is a test flapping issue where 2 panels are open at the same time.
				 // Probably test running too fast? Manually it does not happen. Hack is to
				 // add a second check to look for content in other panel.
				 var newPanelIndex = panelIndex == 0 ? panelIndex+1 : panelIndex-1;
				 actual = that.getPanelContent(cmp, newPanelIndex);
				 if (actual) {
					 return actual;
				 }
			 }
			 return  'Testing Error: Could not read panel content';
		 }, 'Expected text in edit panel for cell is supposed to be "' + expected + '" but was "' + actual + '"');
	 },

	 editPanel : function(cmp, newInput, panelIndex) {
		 panelIndex = panelIndex ? panelIndex : 0;
		 var panel = this.getPanelFromDomElement(cmp, panelIndex);
		 if (!$A.util.isUndefinedOrNull(panel)) {
			 var input = panel.get('v.inputComponent')[0];
			 input.set('v.value', newInput);
			 this.commitCellContent(panel);
		 }
	 },

	 commitCellContent : function(cmp) {
         cmp.getEvent('submit').setParams({
             payload : {
                 index : cmp.get('v.index'),
                 key : cmp.get('v.key'),
                 value : cmp.get('v.inputComponent')[0].get('v.value')
             }
         }).fire();
     },

	 clickOutOfEditPanel : function(cmp) {
		 var input = cmp.find('inputTxt').getElement();
		 $A.test.clickOrTouch(input);
	 },

	 getCellElem : function(cmp, rowIndex, colIndex) {
		 var tbody = document.getElementsByTagName('tbody')[0];
		 var rows = this.getOnlyTrs(tbody.children);
		 var col = rows[rowIndex].children[colIndex];
		 return col;
	 },

	 verifyCellContent : function(cmp, rowIndex, colIndex, expected) {
	     var cell = this.getCellElem(cmp, rowIndex, colIndex);
	     var actual = $A.test.getText(cell);
	     $A.test.assertEquals(expected, actual, 'Cell value is incorrect');
	 },

	 waitForCellContent : function(cmp, rowIndex, colIndex, expected) {
	     var that = this;
	     var actual = '';
	     $A.test.addWaitForWithFailureMessage(expected, function() {
             var cell = that.getCellElem(cmp, rowIndex, colIndex);
             actual = $A.test.getText(cell);
             return actual;
         }, 'Cell value was not updated expecting "' + expected + '" but was "' + actual + '"');
	 }
 })
<|endoftext|>


<commit_before>Tinytest.add('FlowRouter - route() - add route', function (test) {
  var context = {};
  context._routeMap = {};
  context._FlowRoute = function (path, options) {
    this.args = _.toArray(arguments);
  };

  FlowRouter.route.call(context, 'path', 'options');
  test.equal(context._routeMap, {
    'path': new context._FlowRoute('path', 'options')
  });
});

Tinytest.add('FlowRouter - middleware() - add middleware', function (test) {
  var context = {};
  context._middleware = [];

  context._clientRouter = {};
  context._clientRouter.middleware = function (middleware) {
    this.args = this.args || [];
    this.args.push(_.toArray(arguments));
  };

  FlowRouter.middleware.call(context, 'middleware');
  test.equal(context._middleware, [
    'middleware'
  ]);
  test.equal(context._clientRouter.args, [
    ['middleware']
  ]);
});

Tinytest.add('FlowRouter - subscribe() - current route', function (test) {
  var context = {};
  context._getCurrentRoute = function () {
    return {
      subscriptions: function () {
        context.args = context.args || [];
        context.args.push(_.toArray(arguments));
      }
    }
  };

  FlowRouter.subscribe.call(context);
  test.equal(context.args, [
    []
  ]);
});

Tinytest.add('FlowRouter - setState() - set local', function (test) {
  var context = {};
  context._getDefaultStateOptions = FlowRouter._getDefaultStateOptions;
  context._getCurrentRoute = function () {
    return {
      setState: function () {
        context.args = context.args || [];
        context.args.push(_.toArray(arguments));
      }
    }
  };

  var defaultOptions = FlowRouter._getDefaultStateOptions.call(null);
  FlowRouter.setState.call(context, 'name', 'value');
  test.equal(context.args, [
    ['name', 'value', defaultOptions]
  ]);
});

Tinytest.add('FlowRouter - setState() - set global', function (test) {
  var context = {};
  context._globalStates = new ReactiveDict;
  context._getDefaultStateOptions = FlowRouter._getDefaultStateOptions;

  context._clientRouter = {};
  context._clientRouter.setState = function (name, value, options) {
    this.args = this.args || [];
    this.args.push(_.toArray(arguments));
  };

  FlowRouter.setState.call(context, 'name', 'value', {global: true});
  test.equal(context._globalStates.get('name'), 'value');
  test.equal(context._clientRouter.args, [
    ['name', 'value', {global: true}]
  ]);
});

Tinytest.add('FlowRouter - getState() - get local', function (test) {
  var context = {};
  context._globalStates = new ReactiveDict;
  context._globalStates.set('name', 'global-value');
  context._current = 'path';
  context._routeMap = {};
  context._routeMap['path'] = {
    getState: function (name, value, options) {
      this.args = this.args || [];
      this.args.push(_.toArray(arguments));
      return 'local-value';
    }
  };

  var value = FlowRouter.getState.call(context, 'name');
  test.equal(value, 'local-value');
});

Tinytest.add('FlowRouter - getState() - get global', function (test) {
  var context = {};
  context._globalStates = new ReactiveDict;
  context._globalStates.set('name', 'global-value');
  context._current = 'path';
  context._routeMap = {};
  context._routeMap['path'] = {
    getState: function (name, value, options) {
      this.args = this.args || [];
      this.args.push(_.toArray(arguments));
      return null;
    }
  };

  var value = FlowRouter.getState.call(context, 'name');
  test.equal(value, 'global-value');
});

Tinytest.add('FlowRouter - _getDefaultStateOptions() - simple', function (test) {
  var context = {};
  var options = FlowRouter._getDefaultStateOptions.call(context);
  test.equal(options, {
    global: false,
  })
});

Tinytest.add('FlowRouter - _getCurrentRoute() - simple', function (test) {
  var context = {};
  context._current = 'path';
  context._routeMap = {};
  context._routeMap['path'] = 'route';
  var route = FlowRouter._getCurrentRoute.call(context);
  test.equal(route, 'route');
});
<commit_msg>Tweak tests<commit_after>Tinytest.add('FlowRouter - route() - add route', function (test) {
  var context = {};
  context._routeMap = {};
  context._FlowRoute = function (path, options) {
    this.args = _.toArray(arguments);
  };

  FlowRouter.route.call(context, 'path', 'options');
  test.equal(context._routeMap, {
    'path': new context._FlowRoute('path', 'options')
  });
});

Tinytest.add('FlowRouter - middleware() - add middleware', function (test) {
  var context = {};
  context._middleware = [];

  context._clientRouter = {};
  context._clientRouter.middleware = function (middleware) {
    this.args = this.args || [];
    this.args.push(_.toArray(arguments));
  };

  FlowRouter.middleware.call(context, 'middleware');
  test.equal(context._middleware, [
    'middleware'
  ]);
  test.equal(context._clientRouter.args, [
    ['middleware']
  ]);
});

Tinytest.add('FlowRouter - subscribe() - current route', function (test) {
  var context = {};
  context._getCurrentRoute = function () {
    return {
      subscriptions: function () {
        context.args = context.args || [];
        context.args.push(_.toArray(arguments));
      }
    }
  };

  FlowRouter.subscribe.call(context);
  test.equal(context.args, [
    []
  ]);
});

Tinytest.add('FlowRouter - setState() - set local', function (test) {
  var context = {};
  context._getDefaultStateOptions = function () {
    return 'defaults';
  };
  context._getCurrentRoute = function () {
    return {
      setState: function () {
        context.args = context.args || [];
        context.args.push(_.toArray(arguments));
      }
    }
  };

  FlowRouter.setState.call(context, 'name', 'value');
  test.equal(context.args, [
    ['name', 'value', 'defaults']
  ]);
});

Tinytest.add('FlowRouter - setState() - set global', function (test) {
  var context = {};
  context._globalStates = new ReactiveDict;
  context._getDefaultStateOptions = function () {
    return {foo: 'bar'};
  };

  context._clientRouter = {};
  context._clientRouter.setState = function (name, value, options) {
    this.args = this.args || [];
    this.args.push(_.toArray(arguments));
  };

  FlowRouter.setState.call(context, 'name', 'value', {global: true});
  test.equal(context._globalStates.get('name'), 'value');
  test.equal(context._clientRouter.args, [
    ['name', 'value', {global: true, foo: 'bar'}]
  ]);
});

Tinytest.add('FlowRouter - getState() - get local', function (test) {
  var context = {};
  context._globalStates = new ReactiveDict;
  context._globalStates.set('name', 'global-value');
  context._current = 'path';
  context._routeMap = {};
  context._routeMap['path'] = {
    getState: function (name, value, options) {
      this.args = this.args || [];
      this.args.push(_.toArray(arguments));
      return 'local-value';
    }
  };

  var value = FlowRouter.getState.call(context, 'name');
  test.equal(value, 'local-value');
});

Tinytest.add('FlowRouter - getState() - get global', function (test) {
  var context = {};
  context._globalStates = new ReactiveDict;
  context._globalStates.set('name', 'global-value');
  context._current = 'path';
  context._routeMap = {};
  context._routeMap['path'] = {
    getState: function (name, value, options) {
      this.args = this.args || [];
      this.args.push(_.toArray(arguments));
      return null;
    }
  };

  var value = FlowRouter.getState.call(context, 'name');
  test.equal(value, 'global-value');
});

Tinytest.add('FlowRouter - _getDefaultStateOptions() - simple', function (test) {
  var context = {};
  var options = FlowRouter._getDefaultStateOptions.call(context);
  test.equal(options, {
    global: false,
  })
});

Tinytest.add('FlowRouter - _getCurrentRoute() - simple', function (test) {
  var context = {};
  context._current = 'path';
  context._routeMap = {};
  context._routeMap['path'] = 'route';
  var route = FlowRouter._getCurrentRoute.call(context);
  test.equal(route, 'route');
});
<|endoftext|>


<commit_before>import {type, pack} from '../../src/value'
import JsContext from '../../src/contexts/JsContext'

import test from 'tape'

test('JsContext', t => {
  let c = new JsContext()

  t.ok(c instanceof JsContext)
  t.equal(c.constructor.name, 'JsContext')

  t.end()
})

test('JsContext.supportedLanguages', t => {
  let c = new JsContext()

  c.supportedLanguages().then(languages => {
    t.deepEqual(languages, ['js'])
    t.end()
  })
})

test('JsContext.supportsLanguage', t => {
  let c = new JsContext()

  t.plan(2)

  c.supportsLanguage('js').then(result => {
    t.equal(result, true)
  })

  c.supportsLanguage('py').then(result => {
    t.equal(result, false)
  })
})

test('JsContext.analyseCode', t => {
  let c = new JsContext()
  t.plan(10)

  c.analyseCode('Math.pi').then(result => t.deepEqual(result, {
    inputs: [],
    output: null,
    value: 'Math.pi',
    errors: []
  }))

  c.analyseCode('foo').then(result => t.deepEqual(result, {
    inputs: ['foo'],
    output: 'foo',
    value: 'foo',
    errors: []
  }))

  c.analyseCode('let foo\nfoo').then(result => t.deepEqual(result, {
    inputs: [],
    output: 'foo',
    value: 'foo',
    errors: []
  }))

  c.analyseCode('let foo\nfoo * 3').then(result => t.deepEqual(result, {
    inputs: [],
    output: null,
    value: 'foo * 3',
    errors: []
  }))

  c.analyseCode('let foo').then(result => t.deepEqual(result, {
    inputs: [],
    output: 'foo',
    value: 'foo',
    errors: []
  }))

  // Last statement is a declaration (first identifier used)
  c.analyseCode('foo\nbar\nlet baz, urg\n\n').then(result => t.deepEqual(result, {
    inputs: ['foo','bar'],
    output: 'baz',
    value: 'baz',
    errors: []
  }))

  // Last statement is not a declaration or identifier
  c.analyseCode('let foo\n{bar\nlet baz}').then(result => t.deepEqual(result, {
    inputs: ['bar'],
    output: null,
    value: null,
    errors: []
  }))

  // Last statement is not a declaration or identifier
  c.analyseCode('let foo\nbar\nlet baz\ntrue').then(result => t.deepEqual(result, {
    inputs: ['bar'],
    output: null,
    value: 'true',
    errors: []
  }))

  // Variable declaration after usage (this will be a runtime error but this tests static analysis of code regardless)
  c.analyseCode('foo\nlet foo\n').then(result => t.deepEqual(result, {
    inputs: ['foo'],
    output: 'foo',
    value: 'foo',
    errors: []
  }))

  // Syntax error
  c.analyseCode('for(){').then(result => t.deepEqual(result, {
    inputs: [],
    output: null,
    value: null,
    errors: [ { line: 1, column: 4, message: 'SyntaxError: Unexpected token (1:4)'} ]
  }))
})

test('JsContext.executeCode no value', t => {
  let c = new JsContext()
  t.plan(1)

  c.executeCode('if(true){\n  let x = 4\n}\n').then(result => {
    t.deepEqual(result, {
      inputs: [],
      output: null,
      value: null,
      errors: []
    })
  })
})

test('JsContext.executeCode with no inputs, no output, no errors', t => {
  let c = new JsContext()
  t.plan(3)

  c.executeCode('1.1 * 2').then(result => {
    t.deepEqual(result, {
      inputs: [],
      output: null,
      value: { type: 'number', data: 2.2 },
      errors: []
    })
  })

  c.executeCode('let x = 3\nMath.sqrt(x*3)').then(result => {
    t.deepEqual(result, {
      inputs: [],
      output: null,
      value: { type: 'integer', data: 3 },
      errors: []
    })
  })

  c.executeCode('// Multiple lines and comments\nlet x = {}\nObject.assign(x, {a:1})\n').then(result => {
    t.deepEqual(result, {
      inputs: [],
      output: null,
      value: { type: 'object', data: { a: 1 } },
      errors: []
    })
  })
})

test('JsContext.executeCode with inputs, outputs, no errors', t => {
  let c = new JsContext()
  t.plan(2)

  c.executeCode('let b = a*6', {
    a: {type: 'integer', data: 6}
  }).then(result => {
    t.deepEqual(result, {
      inputs: ['a'],
      output: 'b',
      value: { type: 'integer', data: 36 },
      errors: []
    })
  })

  c.executeCode('let c = a*b[1]\nc', {
    a: {type: 'integer', data: 6},
    b: {type: 'array[number]', data: [1, 2, 3]}
  }).then(result => {
    t.deepEqual(result, {
      inputs: ['a', 'b'],
      output: 'c',
      value: { type: 'integer', data: 12 },
      errors: []
    })
  })
})

test('JsContext.executeCode value is multiline', t => {
  let c = new JsContext()
  t.plan(1)

  c.executeCode(`let x = {
    a: 1,
    b: "foo"
  }`).then(result => {
    t.deepEqual(result, {
      inputs: [],
      output: 'x',
      value: { type: 'object', data: { a: 1, b: 'foo'} },
      errors: []
    })
  })
})

test('JsContext.executeCode with errors', t => {
  let c = new JsContext()
  t.plan(3)

  c.executeCode('foo').then(result => {
    t.deepEqual(result.errors, [{line: 1, column: 1, message: 'ReferenceError: foo is not defined'}])
  })
  c.executeCode('1\n2\n foo\n4').then(result => {
    t.deepEqual(result.errors, [{line: 3, column: 2, message: 'ReferenceError: foo is not defined'}])
  })
  c.executeCode(' <>').then(result => {
    t.deepEqual(result.errors, [{line: 1, column: 1, message: 'SyntaxError: Unexpected token (1:1)'}])
  })
})

test.skip('JsContext.runCode', t => {
  let c = new JsContext()
  t.plan(6)

  c.runCode('foo = "bar"')
  t.equal(foo, 'bar', 'can set global variable') // eslint-disable-line no-undef

  c.runCode('foo').then(result => {
    t.deepEqual(result, {errors: null, output: pack('bar')}, 'can get global variable')
  })
  c.runCode('foo + "t_simpson"').then(result => {
    t.deepEqual(result, {errors: null, output: pack('bart_simpson')}, 'can get global variable expression')
  })
  c.runCode('foo\n42\n"lisa"').then(result => {
    t.deepEqual(result, {errors: null, output: pack('lisa')}, 'last value is returned')
  })
  c.runCode('\n').then(result => {
    t.deepEqual(result, {errors: null, output: null}, 'nothing returned when empty')
  })
  c.runCode('let x = 5').then(result => {
    t.deepEqual(result, {errors: null, output: null}, 'nothing returned when last line is statement')
  })
})

test.skip('JsContext.runCode with errors', t => {
  let c = new JsContext()
  t.plan(3)

  c.runCode('foogazi').then(result => {
    t.deepEqual(result, { errors: [ { column: 1, line: 1, message: 'ReferenceError: foogazi is not defined' } ], output: null })
  })
  c.runCode('2*45\nfoogazi').then(result => {
    t.deepEqual(result, { errors: [ { column: 1, line: 2, message: 'ReferenceError: foogazi is not defined' } ], output: null })
  })
  c.runCode('<>').then(result => {
    t.deepEqual(result, { errors: [ { column: 0, line: 0, message: 'SyntaxError: Unexpected token <' } ], output: null })
  })
})

test.skip('JsContext.hasFunction', t => {
  let c = new JsContext()

  t.ok(c.hasFunction('type'))
  t.notOk(c.hasFunction('this_is_not_a_registered_function'))
  t.end()
})

test.skip('JsContext.callFunction without function name', t => {
  let c = new JsContext()
  t.plan(1)

  t.throws(() => {
    c.callFunction()
  })
})

test.skip('JsContext.callFunction with no inputs', t => {
  let c = new JsContext()
  t.plan(1)

  c.callFunction('type').then(result => {
    t.deepEqual(result, {output: pack('unknown'), errors: null})
  })
})

test.skip('JsContext.callFunction with inputs and output', t => {
  let c = new JsContext()
  t.plan(1)

  c.callFunction('type', [pack(1)]).then(result => {
    t.deepEqual(result, {output: pack('integer'), errors: null})
  })
})

test.skip('JsContext.callFunction with named arguments', t => {
  let c = new JsContext()
  t.plan(7)

  // TODO this uses a stochatic function for testing! Use a deterministic function with
  // named parameters

  c.callFunction('random_uniform', [10], {}, {pack: false}).then(result => {
    t.equal(type(result.output), 'array')
    t.equal(result.output.length, 10)
  })

  c.callFunction('random_uniform', [], {n: 10}, {pack: false}).then(result => {
    t.equal(type(result.output), 'array')
    t.equal(result.output.length, 10)
  })

  c.callFunction('random_uniform', [], {min: 100, n: 1}, {pack: false}).then(result => {
    t.equal(type(result.output), 'float')
    t.ok(result.output < 100)
  })

  c.callFunction('random_uniform', [], {min: 100, foo: 1}, {pack: false})
    .then(() => {
      t.fail('should not resolve')
    })
    .catch(error => {
      t.equal(error.message, 'Invalid named argument "foo"; valid names are "n", "min", "max"')
    })

})

test.skip('JsContext.callFunction with error', t => {
  let c = new JsContext()
  t.plan(1)
  c._functions['foo'] = () => {
    throw new Error('nope')
  }
  c.callFunction('foo').then(result => {
    t.deepEqual(result, {errors: [ { column: 0, line: 0, message: 'Error: nope' } ], output: null})
  })
})
<commit_msg>Test with global variable<commit_after>import {type, pack} from '../../src/value'
import JsContext from '../../src/contexts/JsContext'

import test from 'tape'

test('JsContext', t => {
  let c = new JsContext()

  t.ok(c instanceof JsContext)
  t.equal(c.constructor.name, 'JsContext')

  t.end()
})

test('JsContext.supportedLanguages', t => {
  let c = new JsContext()

  c.supportedLanguages().then(languages => {
    t.deepEqual(languages, ['js'])
    t.end()
  })
})

test('JsContext.supportsLanguage', t => {
  let c = new JsContext()

  t.plan(2)

  c.supportsLanguage('js').then(result => {
    t.equal(result, true)
  })

  c.supportsLanguage('py').then(result => {
    t.equal(result, false)
  })
})

test('JsContext.analyseCode', t => {
  let c = new JsContext()
  t.plan(10)

  c.analyseCode('Math.pi').then(result => t.deepEqual(result, {
    inputs: [],
    output: null,
    value: 'Math.pi',
    errors: []
  }))

  c.analyseCode('foo').then(result => t.deepEqual(result, {
    inputs: ['foo'],
    output: 'foo',
    value: 'foo',
    errors: []
  }))

  c.analyseCode('let foo\nfoo').then(result => t.deepEqual(result, {
    inputs: [],
    output: 'foo',
    value: 'foo',
    errors: []
  }))

  c.analyseCode('let foo\nfoo * 3').then(result => t.deepEqual(result, {
    inputs: [],
    output: null,
    value: 'foo * 3',
    errors: []
  }))

  c.analyseCode('let foo').then(result => t.deepEqual(result, {
    inputs: [],
    output: 'foo',
    value: 'foo',
    errors: []
  }))

  // Last statement is a declaration (first identifier used)
  c.analyseCode('foo\nbar\nlet baz, urg\n\n').then(result => t.deepEqual(result, {
    inputs: ['foo','bar'],
    output: 'baz',
    value: 'baz',
    errors: []
  }))

  // Last statement is not a declaration or identifier
  c.analyseCode('let foo\n{bar\nlet baz}').then(result => t.deepEqual(result, {
    inputs: ['bar'],
    output: null,
    value: null,
    errors: []
  }))

  // Last statement is not a declaration or identifier
  c.analyseCode('let foo\nbar\nlet baz\ntrue').then(result => t.deepEqual(result, {
    inputs: ['bar'],
    output: null,
    value: 'true',
    errors: []
  }))

  // Variable declaration after usage (this will be a runtime error but this tests static analysis of code regardless)
  c.analyseCode('foo\nlet foo\n').then(result => t.deepEqual(result, {
    inputs: ['foo'],
    output: 'foo',
    value: 'foo',
    errors: []
  }))

  // Syntax error
  c.analyseCode('for(){').then(result => t.deepEqual(result, {
    inputs: [],
    output: null,
    value: null,
    errors: [ { line: 1, column: 4, message: 'SyntaxError: Unexpected token (1:4)'} ]
  }))
})

test('JsContext.executeCode no value', t => {
  let c = new JsContext()
  t.plan(2)

  c.executeCode('\n').then(result => {
    t.deepEqual(result.value, null, 'nothing returned when empty')
  })

  c.executeCode('if(true){\n  let x = 4\n}\n').then(result => {
    t.deepEqual(result, {
      inputs: [],
      output: null,
      value: null,
      errors: []
    })
  })
})

test('JsContext.executeCode with no inputs, no output, no errors', t => {
  let c = new JsContext()
  t.plan(3)

  c.executeCode('1.1 * 2').then(result => {
    t.deepEqual(result, {
      inputs: [],
      output: null,
      value: { type: 'number', data: 2.2 },
      errors: []
    })
  })

  c.executeCode('let x = 3\nMath.sqrt(x*3)').then(result => {
    t.deepEqual(result, {
      inputs: [],
      output: null,
      value: { type: 'integer', data: 3 },
      errors: []
    })
  })

  c.executeCode('// Multiple lines and comments\nlet x = {}\nObject.assign(x, {a:1})\n').then(result => {
    t.deepEqual(result, {
      inputs: [],
      output: null,
      value: { type: 'object', data: { a: 1 } },
      errors: []
    })
  })
})

test('JsContext.executeCode with inputs, outputs, no errors', t => {
  let c = new JsContext()
  t.plan(2)

  c.executeCode('let b = a*6', {
    a: {type: 'integer', data: 6}
  }).then(result => {
    t.deepEqual(result, {
      inputs: ['a'],
      output: 'b',
      value: { type: 'integer', data: 36 },
      errors: []
    })
  })

  c.executeCode('let c = a*b[1]\nc', {
    a: {type: 'integer', data: 6},
    b: {type: 'array[number]', data: [1, 2, 3]}
  }).then(result => {
    t.deepEqual(result, {
      inputs: ['a', 'b'],
      output: 'c',
      value: { type: 'integer', data: 12 },
      errors: []
    })
  })
})

test('JsContext.executeCode value is multiline', t => {
  let c = new JsContext()
  t.plan(1)

  c.executeCode(`let x = {
    a: 1,
    b: "foo"
  }`).then(result => {
    t.deepEqual(result, {
      inputs: [],
      output: 'x',
      value: { type: 'object', data: { a: 1, b: 'foo'} },
      errors: []
    })
  })
})

test('JsContext.executeCode with errors', t => {
  let c = new JsContext()
  t.plan(3)

  c.executeCode('foo').then(result => {
    t.deepEqual(result.errors, [{line: 1, column: 1, message: 'ReferenceError: foo is not defined'}])
  })
  c.executeCode('1\n2\n foo\n4').then(result => {
    t.deepEqual(result.errors, [{line: 3, column: 2, message: 'ReferenceError: foo is not defined'}])
  })
  c.executeCode(' <>').then(result => {
    t.deepEqual(result.errors, [{line: 1, column: 1, message: 'SyntaxError: Unexpected token (1:1)'}])
  })
})

test('JsContext.executeCode with global variables', t => {
  let c = new JsContext()
  t.plan(3)

  c.executeCode('foo = "bar"')

  c.executeCode('foo').then(result => {
    t.deepEqual(result.value, {type: 'string', data: 'bar'}, 'can get global variable')
  })

  c.executeCode('foo + "t_simpson"').then(result => {
    t.deepEqual(result.value, {type: 'string', data: 'bart_simpson'}, 'can get global variable expression')
  })

  c.executeCode('foo = 42')

  c.executeCode('foo').then(result => {
    t.deepEqual(result.value, {type: 'integer', data: 42}, 'can change global variable')
  })
})

test.skip('JsContext.hasFunction', t => {
  let c = new JsContext()

  t.ok(c.hasFunction('type'))
  t.notOk(c.hasFunction('this_is_not_a_registered_function'))
  t.end()
})

test.skip('JsContext.callFunction without function name', t => {
  let c = new JsContext()
  t.plan(1)

  t.throws(() => {
    c.callFunction()
  })
})

test.skip('JsContext.callFunction with no inputs', t => {
  let c = new JsContext()
  t.plan(1)

  c.callFunction('type').then(result => {
    t.deepEqual(result, {output: pack('unknown'), errors: null})
  })
})

test.skip('JsContext.callFunction with inputs and output', t => {
  let c = new JsContext()
  t.plan(1)

  c.callFunction('type', [pack(1)]).then(result => {
    t.deepEqual(result, {output: pack('integer'), errors: null})
  })
})

test.skip('JsContext.callFunction with named arguments', t => {
  let c = new JsContext()
  t.plan(7)

  // TODO this uses a stochatic function for testing! Use a deterministic function with
  // named parameters

  c.callFunction('random_uniform', [10], {}, {pack: false}).then(result => {
    t.equal(type(result.output), 'array')
    t.equal(result.output.length, 10)
  })

  c.callFunction('random_uniform', [], {n: 10}, {pack: false}).then(result => {
    t.equal(type(result.output), 'array')
    t.equal(result.output.length, 10)
  })

  c.callFunction('random_uniform', [], {min: 100, n: 1}, {pack: false}).then(result => {
    t.equal(type(result.output), 'float')
    t.ok(result.output < 100)
  })

  c.callFunction('random_uniform', [], {min: 100, foo: 1}, {pack: false})
    .then(() => {
      t.fail('should not resolve')
    })
    .catch(error => {
      t.equal(error.message, 'Invalid named argument "foo"; valid names are "n", "min", "max"')
    })

})

test.skip('JsContext.callFunction with error', t => {
  let c = new JsContext()
  t.plan(1)
  c._functions['foo'] = () => {
    throw new Error('nope')
  }
  c.callFunction('foo').then(result => {
    t.deepEqual(result, {errors: [ { column: 0, line: 0, message: 'Error: nope' } ], output: null})
  })
})
<|endoftext|>


<commit_before>/*global module */
/*global test */
/*global equal */
/*global ok */
/*global expect */
/*global fuzzy_equal */
/*global BEZIER */

module("BezierCurve - BezierCurve3");

test("Empty Constructor", function () {
	expect(1);

	try {
		var bz = new BEZIER.core.beziercurve3();
	} catch (e) {
		equal(e.type, "illegalargumenterror", "Throws error on empty constructor");
	}
});

test("No Points", function () {
	expect(1);

	try {
		var bz = new BEZIER.core.beziercurve3([]);
	} catch (e) {
		equal(e.type, "illegalargumenterror", "Throws error when no control point are given.");
	}
});

test("No Link Constructor", function () {

	var l = [BEZIER.core.dim3(0, 0, 0), BEZIER.core.dim3(1, 1, 1)];
	var bc3 =  new BEZIER.core.beziercurve3(l);

	equal(bc3.num_points(), 2);
	l.push(BEZIER.core.dim3(2, 2, 2));
	equal(bc3.num_points(), 2);
});

test("Get Point", function () {

	var bc3 =  new BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 0, 0), BEZIER.core.dim3(1, 1, 1)]);

	var d1 = bc3.get_point(0);
	var d2 = bc3.get_point(1);
	var d3 = bc3.get_point(2);
	var dn1 = bc3.get_point(-1);

	ok(d1, "D1 != null");
	ok(d2, "D2 != null");
	ok(!d3, "D3 == null");
	ok(d1 !== d2,   "D1 !== D2");
	ok(!dn1, "D3 is not null");
});

test("Num Points - One", function () {
	var bc3 =  new BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 1, 2)]);
	equal(bc3.num_points(), 1, "Point Length");
});

test("Num Points - Two", function () {
	var bc3 =  new BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 1, 2), BEZIER.core.dim3(0, 1, 2)]);
	equal(bc3.num_points(), 2, "Point Length");
});

test("Calculate - Negative T", function () {
	expect(1);

	var bc3 =  new BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 1, 2), BEZIER.core.dim3(1, 2, 3)]);

	try {
		bc3.calculate(-0.1);
	} catch (e) {
		equal(e.type, "illegalargumenterror", "T is out of range:" + e.message);
	}

});

test("Calculate - T > 1", function () {
	expect(1);

	var bc3 =  new BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 1, 2), BEZIER.core.dim3(1, 2, 3)]);

	try {
		bc3.calculate(1.1);
	} catch (e) {
		equal(e.type, "illegalargumenterror", "T is out of range:" + e.message);
	}

});

test("Calculate - Simple", function () {

	var bc3 =  new BEZIER.core.beziercurve3([new BEZIER.core.dim3(0, 1, 2), new BEZIER.core.dim3(1, 2, 3)]);

	var t0   = bc3.calculate(0);
	var t0p5 = bc3.calculate(0.5);
	var t1   = bc3.calculate(1);

	equal(t0.x, 0);
	equal(t0.y, 1);
	equal(t0.z, 2);

	equal(t0p5.x, 0.5);
	equal(t0p5.y, 1.5);
	equal(t0p5.z, 2.5);

	equal(t1.x, 1);
	equal(t1.y, 2);
	equal(t1.z, 3);
});

<commit_msg>re-org to better suit js best practices.<commit_after>/*global module */
/*global test */
/*global equal */
/*global ok */
/*global expect */
/*global fuzzy_equal */
/*global BEZIER */

module("BezierCurve - BezierCurve3");

test("Empty Constructor", function () {
	expect(1);

	try {
		var bz = BEZIER.core.beziercurve3();
	} catch (e) {
		equal(e.type, "illegalargumenterror", "Throws error on empty constructor");
	}
});

test("No Points", function () {
	expect(1);

	try {
		var bz = BEZIER.core.beziercurve3([]);
	} catch (e) {
		equal(e.type, "illegalargumenterror", "Throws error when no control point are given.");
	}
});

test("No Link Constructor", function () {

	var l = [BEZIER.core.dim3(0, 0, 0), BEZIER.core.dim3(1, 1, 1)];
	var bc3 =  BEZIER.core.beziercurve3(l);

	equal(bc3.num_points(), 2);
	l.push(BEZIER.core.dim3(2, 2, 2));
	equal(bc3.num_points(), 2);
});

test("Get Point", function () {

	var bc3 =  BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 0, 0), BEZIER.core.dim3(1, 1, 1)]);

	var d1 = bc3.get_point(0);
	var d2 = bc3.get_point(1);
	var d3 = bc3.get_point(2);
	var dn1 = bc3.get_point(-1);

	ok(d1, "D1 != null");
	ok(d2, "D2 != null");
	ok(!d3, "D3 == null");
	ok(d1 !== d2,   "D1 !== D2");
	ok(!dn1, "D3 is not null");
});

test("Num Points - One", function () {
	var bc3 =  BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 1, 2)]);
	equal(bc3.num_points(), 1, "Point Length");
});

test("Num Points - Two", function () {
	var bc3 =  BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 1, 2), BEZIER.core.dim3(0, 1, 2)]);
	equal(bc3.num_points(), 2, "Point Length");
});

test("Calculate - Negative T", function () {
	expect(1);

	var bc3 =  BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 1, 2), BEZIER.core.dim3(1, 2, 3)]);

	try {
		bc3.calculate(-0.1);
	} catch (e) {
		equal(e.type, "illegalargumenterror", "T is out of range:" + e.message);
	}

});

test("Calculate - T > 1", function () {
	expect(1);

	var bc3 =  BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 1, 2), BEZIER.core.dim3(1, 2, 3)]);

	try {
		bc3.calculate(1.1);
	} catch (e) {
		equal(e.type, "illegalargumenterror", "T is out of range:" + e.message);
	}

});

test("Calculate - Simple", function () {

	var bc3 =  BEZIER.core.beziercurve3([BEZIER.core.dim3(0, 1, 2), BEZIER.core.dim3(1, 2, 3)]);

	var t0   = bc3.calculate(0);
	var t0p5 = bc3.calculate(0.5);
	var t1   = bc3.calculate(1);

	equal(t0.x, 0);
	equal(t0.y, 1);
	equal(t0.z, 2);

	equal(t0p5.x, 0.5);
	equal(t0p5.y, 1.5);
	equal(t0p5.z, 2.5);

	equal(t1.x, 1);
	equal(t1.y, 2);
	equal(t1.z, 3);
});

<|endoftext|>


<commit_before>var expect = require('chai').expect;
var sinon = require('sinon');
var sandboxed = require('sandboxed-module');

var testUtils = require('./util/util');

describe('integrationSystem', function() {

    it('should run', function() {
        var clock = sinon.useFakeTimers();

        var loadMock = testUtils.createModuleMock();
        var cpuMock = testUtils.createModuleMock();
        var memoryMock = testUtils.createModuleMock();
        var temperatureMock = testUtils.createModuleMock();

        var System = sandboxed.require('../lib/modules/System', {
            requires: {
                './memory': memoryMock,
                './load': loadMock,
                './cpu': cpuMock,
                './temperature': temperatureMock
            }
        });

        var mySystem = new System({}, [loadMock, cpuMock, memoryMock, temperatureMock]);

        mySystem.start();

        clock.tick(40000);

        expect(memoryMock.start.callCount).to.equal(1);
        expect(memoryMock.stop.callCount).to.equal(1);

        expect(cpuMock.start.callCount).to.equal(1);
        expect(cpuMock.stop.callCount).to.equal(1);

        expect(loadMock.start.callCount).to.equal(1);
        expect(loadMock.stop.callCount).to.equal(0);

        expect(temperatureMock.start.callCount).to.equal(1);
        expect(temperatureMock.stop.callCount).to.equal(1);

        clock.restore();
    });

    it('should run with a switchInterval', function() {
        var clock = sinon.useFakeTimers();

        var loadMock = testUtils.createModuleMock();
        var cpuMock = testUtils.createModuleMock();
        var memoryMock = testUtils.createModuleMock();
        var temperatureMock = testUtils.createModuleMock();

        var System = sandboxed.require('../lib/modules/System', {
            requires: {
                './memory': memoryMock,
                './load': loadMock,
                './cpu': cpuMock,
                './temperature': temperatureMock
            }
        });

        var mySystem = new System({ switchInterval: 5000}, [loadMock, cpuMock, memoryMock, temperatureMock]);

        mySystem.start();

        clock.tick(30000);

        expect(memoryMock.start.callCount).to.equal(2);
        expect(memoryMock.stop.callCount).to.equal(1);

        expect(cpuMock.start.callCount).to.equal(2);
        expect(cpuMock.stop.callCount).to.equal(2);

        expect(loadMock.start.callCount).to.equal(1);
        expect(loadMock.stop.callCount).to.equal(1);

        expect(temperatureMock.start.callCount).to.equal(1);
        expect(temperatureMock.stop.callCount).to.equal(1);

        clock.restore();
    });

    it('should run with a pauseInterval', function() {
        var clock = sinon.useFakeTimers();

        var loadMock = testUtils.createModuleMock();
        var cpuMock = testUtils.createModuleMock();
        var memoryMock = testUtils.createModuleMock();
        var temperatureMock = testUtils.createModuleMock();

        var System = sandboxed.require('../lib/modules/System', {
            requires: {
                './memory': memoryMock,
                './load': loadMock,
                './cpu': cpuMock,
                './temperature': temperatureMock
            }
        });

        var mySystem = new System({ pause: 5000}, [loadMock, cpuMock, memoryMock, temperatureMock]);

        mySystem.start();

        clock.tick(30000);

        expect(memoryMock.start.callCount).to.equal(1);
        expect(memoryMock.stop.callCount).to.equal(1);

        expect(cpuMock.start.callCount).to.equal(1);
        expect(cpuMock.stop.callCount).to.equal(1);

        expect(loadMock.start.callCount).to.equal(0);
        expect(loadMock.stop.callCount).to.equal(0);

        expect(temperatureMock.start.callCount).to.equal(1);
        expect(temperatureMock.stop.callCount).to.equal(0);

        clock.restore();
    });

    it('should run and stop', function() {
        var clock = sinon.useFakeTimers();

        var loadMock = testUtils.createModuleMock();
        var cpuMock = testUtils.createModuleMock();
        var memoryMock = testUtils.createModuleMock();
        var temperatureMock = testUtils.createModuleMock();

        var System = sandboxed.require('../lib/modules/System', {
            requires: {
                './memory': memoryMock,
                './load': loadMock,
                './cpu': cpuMock,
                './temperature': temperatureMock
            }
        });

        var mySystem = new System({ pause: 5000}, [loadMock, cpuMock, memoryMock, temperatureMock]);

        mySystem.start();

        clock.tick(30000);

        mySystem.stop();

        expect(memoryMock.start.callCount).to.equal(1);
        expect(memoryMock.stop.callCount).to.equal(1);

        expect(cpuMock.start.callCount).to.equal(1);
        expect(cpuMock.stop.callCount).to.equal(1);

        expect(loadMock.start.callCount).to.equal(0);
        expect(loadMock.stop.callCount).to.equal(0);

        expect(temperatureMock.start.callCount).to.equal(1);
        expect(temperatureMock.stop.callCount).to.equal(0);

        clock.restore();
    });
});
<commit_msg>whitespace cleanup<commit_after>var expect = require('chai').expect;
var sinon = require('sinon');
var sandboxed = require('sandboxed-module');

var testUtils = require('./util/util');

describe('integrationSystem', function() {

    it('should run', function() {
        var clock = sinon.useFakeTimers();

        var loadMock = testUtils.createModuleMock();
        var cpuMock = testUtils.createModuleMock();
        var memoryMock = testUtils.createModuleMock();
        var temperatureMock = testUtils.createModuleMock();

        var System = sandboxed.require('../lib/modules/System', {
            requires: {
                './memory': memoryMock,
                './load': loadMock,
                './cpu': cpuMock,
                './temperature': temperatureMock
            }
        });

        var mySystem = new System({}, [loadMock, cpuMock, memoryMock, temperatureMock]);

        mySystem.start();

        clock.tick(40000);

        expect(memoryMock.start.callCount).to.equal(1);
        expect(memoryMock.stop.callCount).to.equal(1);

        expect(cpuMock.start.callCount).to.equal(1);
        expect(cpuMock.stop.callCount).to.equal(1);

        expect(loadMock.start.callCount).to.equal(1);
        expect(loadMock.stop.callCount).to.equal(0);

        expect(temperatureMock.start.callCount).to.equal(1);
        expect(temperatureMock.stop.callCount).to.equal(1);

        clock.restore();
    });

    it('should run with a switchInterval', function() {
        var clock = sinon.useFakeTimers();

        var loadMock = testUtils.createModuleMock();
        var cpuMock = testUtils.createModuleMock();
        var memoryMock = testUtils.createModuleMock();
        var temperatureMock = testUtils.createModuleMock();

        var System = sandboxed.require('../lib/modules/System', {
            requires: {
                './memory': memoryMock,
                './load': loadMock,
                './cpu': cpuMock,
                './temperature': temperatureMock
            }
        });

        var mySystem = new System({switchInterval: 5000}, [loadMock, cpuMock, memoryMock, temperatureMock]);

        mySystem.start();

        clock.tick(30000);

        expect(memoryMock.start.callCount).to.equal(2);
        expect(memoryMock.stop.callCount).to.equal(1);

        expect(cpuMock.start.callCount).to.equal(2);
        expect(cpuMock.stop.callCount).to.equal(2);

        expect(loadMock.start.callCount).to.equal(1);
        expect(loadMock.stop.callCount).to.equal(1);

        expect(temperatureMock.start.callCount).to.equal(1);
        expect(temperatureMock.stop.callCount).to.equal(1);

        clock.restore();
    });

    it('should run with a pauseInterval', function() {
        var clock = sinon.useFakeTimers();

        var loadMock = testUtils.createModuleMock();
        var cpuMock = testUtils.createModuleMock();
        var memoryMock = testUtils.createModuleMock();
        var temperatureMock = testUtils.createModuleMock();

        var System = sandboxed.require('../lib/modules/System', {
            requires: {
                './memory': memoryMock,
                './load': loadMock,
                './cpu': cpuMock,
                './temperature': temperatureMock
            }
        });

        var mySystem = new System({pause: 5000}, [loadMock, cpuMock, memoryMock, temperatureMock]);

        mySystem.start();

        clock.tick(30000);

        expect(memoryMock.start.callCount).to.equal(1);
        expect(memoryMock.stop.callCount).to.equal(1);

        expect(cpuMock.start.callCount).to.equal(1);
        expect(cpuMock.stop.callCount).to.equal(1);

        expect(loadMock.start.callCount).to.equal(0);
        expect(loadMock.stop.callCount).to.equal(0);

        expect(temperatureMock.start.callCount).to.equal(1);
        expect(temperatureMock.stop.callCount).to.equal(0);

        clock.restore();
    });

    it('should run and stop', function() {
        var clock = sinon.useFakeTimers();

        var loadMock = testUtils.createModuleMock();
        var cpuMock = testUtils.createModuleMock();
        var memoryMock = testUtils.createModuleMock();
        var temperatureMock = testUtils.createModuleMock();

        var System = sandboxed.require('../lib/modules/System', {
            requires: {
                './memory': memoryMock,
                './load': loadMock,
                './cpu': cpuMock,
                './temperature': temperatureMock
            }
        });

        var mySystem = new System({pause: 5000}, [loadMock, cpuMock, memoryMock, temperatureMock]);

        mySystem.start();

        clock.tick(30000);

        mySystem.stop();

        expect(memoryMock.start.callCount).to.equal(1);
        expect(memoryMock.stop.callCount).to.equal(1);

        expect(cpuMock.start.callCount).to.equal(1);
        expect(cpuMock.stop.callCount).to.equal(1);

        expect(loadMock.start.callCount).to.equal(0);
        expect(loadMock.stop.callCount).to.equal(0);

        expect(temperatureMock.start.callCount).to.equal(1);
        expect(temperatureMock.stop.callCount).to.equal(0);

        clock.restore();
    });
});
<|endoftext|>


<commit_before>'use strict';

module.exports = (function () {

    let test2Page = {

        pageTest2: 'http://localhost:8001/test2.html',
        textGreen: 'Green',
        dropdownColors: '#dropdown-colors'

    };

    return test2Page;

})();
<commit_msg>Updated page objects for tests<commit_after>'use strict';

module.exports = (function () {

    let test2Page = {

        pageTest2: 'http://localhost:8001/test2.html',
        textGold: 'Gold',
        dropdownColors: '#dropdown-colors',
        blockSelectedColor: '#block-selected-color'

    };

    return test2Page;

})();
<|endoftext|>


<commit_before>import $ from 'wee-dom';
import $events from 'wee-events';
import { createDiv, createSingleDiv, createMultiDiv, resetDOM } from '../helpers/dom';

function removeEvents() {
	let elements = document.body.getElementsByTagName('*');

	for (let i = elements.length; i--;) {
		let oldElement = elements[i];
		let newElement = oldElement.cloneNode(true);

		oldElement.parentNode.replaceChild(newElement, oldElement);
	}

	$events.off();
}

function triggerEvent(el, type) {
	let e = document.createEvent('HTMLEvents');
	e.initEvent(type, false, true);
	el.dispatchEvent(e);
}

describe('Events', () => {
	describe('on', () => {
		beforeEach(() => {
			createSingleDiv();
			createMultiDiv();
		});
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should bind a single event to a single element', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});

		it('should bind multiple events to a single element', () => {
			$events.on({
				'.test': {
					click() {
						$('.test')[0].style.backgroundColor = 'red';
					},
					mouseenter() {
						$('.test')[0].style.backgroundColor = 'purple';
					}
				}
			});

			triggerEvent($('.test')[0], 'click');
			expect($('.test')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.test')[0], 'mouseenter');
			expect($('.test')[0].style.backgroundColor).to.equal('purple');
		});

		it('should bind multiple events to multiple elements', () => {
			$events.on({
				'#first': {
					click() {
						$('#first')[0].style.backgroundColor = 'red';
					},
					mouseenter() {
						$('#first')[0].style.backgroundColor = 'purple';
					}
				},
				'.other-class': {
					click() {
						$('.other-class')[0].style.backgroundColor = 'red';
					},
					mouseenter() {
						$('.other-class')[0].style.backgroundColor = 'purple';
					}
				}
			});

			triggerEvent($('#first')[0], 'click');
			expect($('#first')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('#first')[0], 'mouseenter');
			expect($('#first')[0].style.backgroundColor).to.equal('purple');
			triggerEvent($('.other-class')[0], 'click');
			expect($('.other-class')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.other-class')[0], 'mouseenter');
			expect($('.other-class')[0].style.backgroundColor).to.equal('purple');
		});

		it('should inject the event and element into the callback', () => {
			$events.on('.test', 'click', (e, el) => {
				expect(el.className).to.equal('test');
				expect(e.type).to.equal('click');
			});

			triggerEvent($('.test')[0], 'click');
		});

		it('should bind multiple events to a single element selection', () => {
			$events.on('.test', {
				click() {
					$('.test')[0].style.backgroundColor = 'red';
				},
				mouseenter() {
					$('.test')[0].style.backgroundColor = 'purple';
				}
			});

			triggerEvent($('.test')[0], 'click');
			expect($('.test')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.test')[0], 'mouseenter');
			expect($('.test')[0].style.backgroundColor).to.equal('purple');
		})

		describe('once', () => {
			it('should bind an event that fires only once', () => {
				$events.on('.test', 'click', () => {
					let bgColor = $('.test')[0].style.backgroundColor;

					$('.test')[0].style.backgroundColor =
						bgColor === 'red' ? 'purple' : 'red';
				}, {
					once: true
				});

				triggerEvent($('.test')[0], 'click');
				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('targ', () => {
			// TODO: what does this do?
			it('targ', () => {
				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					targ: '.test'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});

			// TODO: get clarification
			it('should set ref on targ', () => {
				before(createSingleDiv);

				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red'
				}, {
					targ: 'ref:test'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('args', () => {
			it('can add injected arguments', () => {
				$events.on('.test', 'click', (e, el, arg1, arg2) => {
					expect(arg1).to.equal('arg1');
					expect(arg2).to.equal('arg2');
				}, {
					args: ['arg1', 'arg2']
				});

				triggerEvent($('.test')[0], 'click');
			});
		});

		describe('scope', () => {
			it('can add change the scope of the callback', () => {
				let test = {
					param: 'test',
					bind() {
						$events.on('.test', 'click', function() {
							expect(this.param).to.equal('test');
						}, {
							scope: this
						});
					}
				}

				test.bind();

				triggerEvent($('.test')[0], 'click');
			});
		});

		describe('delegate', () => {
			it('should delegate bound events to specified ancestor', () => {
				$events.on('.new-el', 'click', (e, el) => {
					el.style.backgroundColor = 'red';
				}, {
					delegate: 'body'
				});

				document.body.appendChild(createDiv({ className: 'new-el' }));

				triggerEvent($('.new-el')[0], 'click');
			});
		});

		describe('context', () => {
			it('should use provided context for selection', () => {
				// TODO: figure out the best way to test that it's actually
				// TODO: using provided context
				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					context: 'body'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('namespace', () => {
			it('should add a namespace to event', () => {
				// TODO: find the best way to test for namespace existence
				$events.on('.test', 'click', function() {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					namespace: 'namespace'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});
	});

	describe('trigger', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should trigger event for matching selection', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			$events.trigger('.test', 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});
	});

	describe('touch', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should bind touch event', () => {
			$events.on('.test', 'swipeLeft', () => {
				$('.test')[0].style.backgroundColor = 'red';
			}, {
				distance: 150,
				movement: 20
			});

			$events.trigger('.test', 'swipeLeft');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});
	});

	describe('bound', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('it should return an array of all bound events', () => {
			$events.on({
				'.test': {
					click() {
						return 'click';
					},
					mouseenter() {
						return 'mouseenter';
					}
				}
			});

			expect($events.bound()).to.be.an('array');
			expect($events.bound()[0]).to.be.an('object');
			expect($events.bound()[0].el.className).to.equal('test');
			expect($events.bound()[0].ev).to.equal('click');
			expect($events.bound()[0].evt).to.equal('click');
			expect($events.bound()[0].fn()).to.equal('click');

			expect($events.bound()[1].el.className).to.equal('test');
			expect($events.bound()[1].ev).to.equal('mouseenter');
			expect($events.bound()[1].evt).to.equal('mouseenter');
			expect($events.bound()[1].fn()).to.equal('mouseenter');
		});

		// TODO: finish this test
		// it('should check delegated selector against targeted selector', () => {
		// 	$events.on('ref:test', 'click', (e, el) => {
		// 		el.style.backgroundColor = 'red';
		// 	}, {
		// 		delegate: 'ref:test'
		// 	});
		//
		// 	createDiv({
		// 		className: 'new-el'
		// 	}, {
		// 		'data-ref': 'test'
		// 	}, true);
		//
		// 	triggerEvent($('ref:test')[0], 'click');
		// });
	});

	describe('off', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should remove a bound element', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off('.test');

			expect($events.bound().length).to.equal(0);
		});

		it('should remove a bound element by namespace', () => {
			$events.on('.test', 'click.namespace', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off(null, '.namespace');

			expect($events.bound().length).to.equal(0);
		});
	});

	describe('addEvent', () => {
		beforeEach(() => {
			createSingleDiv();
			createMultiDiv();
		});
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should register custom event', () => {
			$events.addEvent('pressHold', function(el, fn, conf) {
				$events.on(el, 'mousedown.pressHold', function(e, el) {
					expect(el.className).to.equal('test');
				}, conf);

				$events.on(el, 'mouseup.pressHold', function(e, el) {
					expect(el.className).to.equal('test');
				});
			}, function(el, fn) {
				$events.off(el, 'mouseup.pressHold', fn);
			});

			$events.on('.test', 'pressHold', function(e, el) {
				$('.test')[0].style.backgroundColor = 'red';
			});

			$events.trigger('.test', 'pressHold');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off('.test', null, (e) => {
				// TODO: Find a better way to test this
			});
		});
	});

	// TODO: finish this test - line 99
	// describe('init', () => {
	// 	beforeEach(createSingleDiv);
	// 	afterEach(resetDOM);
	//
	// 	it('should fire event immediately', () => {
	// 		$events.on('.test', 'click', () => {
	// 			$('.test')[0].style.backgroundColor = 'red';
	// 		}, {
	// 			init: true
	// 		});
	//
	// 		triggerEvent($('.test')[0], 'click');
	//
	// 		expect($('.test')[0].style.backgroundColor).to.equal('red');
	// 	});
	// });
});<commit_msg>Shorten scope test and ensure callback execution<commit_after>import $ from 'wee-dom';
import $events from 'wee-events';
import { createDiv, createSingleDiv, createMultiDiv, resetDOM } from '../helpers/dom';

function removeEvents() {
	let elements = document.body.getElementsByTagName('*');

	for (let i = elements.length; i--;) {
		let oldElement = elements[i];
		let newElement = oldElement.cloneNode(true);

		oldElement.parentNode.replaceChild(newElement, oldElement);
	}

	$events.off();
}

function triggerEvent(el, type) {
	let e = document.createEvent('HTMLEvents');
	e.initEvent(type, false, true);
	el.dispatchEvent(e);
}

describe('Events', () => {
	describe('on', () => {
		beforeEach(() => {
			createSingleDiv();
			createMultiDiv();
		});
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should bind a single event to a single element', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});

		it('should bind multiple events to a single element', () => {
			$events.on({
				'.test': {
					click() {
						$('.test')[0].style.backgroundColor = 'red';
					},
					mouseenter() {
						$('.test')[0].style.backgroundColor = 'purple';
					}
				}
			});

			triggerEvent($('.test')[0], 'click');
			expect($('.test')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.test')[0], 'mouseenter');
			expect($('.test')[0].style.backgroundColor).to.equal('purple');
		});

		// TODO: Try to figure out the best way to test multiple bindings
		it('should bind multiple events to multiple elements', () => {
			$events.on({
				'#first': {
					click(e, el) {
						el.style.backgroundColor = 'red';
					},
					mouseenter(e, el) {
						el.style.backgroundColor = 'purple';
					}
				},
				'.child': {
					click(e, el) {
						el.style.backgroundColor = 'red';
					},
					mouseenter(e, el) {
						el.style.backgroundColor = 'purple';
					}
				}
			});

			triggerEvent($('#first')[0], 'click');
			expect($('#first')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('#first')[0], 'mouseenter');
			expect($('#first')[0].style.backgroundColor).to.equal('purple');

			triggerEvent($('.child')[0], 'click');
			expect($('.child')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.child')[0], 'mouseenter');
			expect($('.child')[0].style.backgroundColor).to.equal('purple');

			// Reset background color
			$('.child')[0].style.backgroundColor = '';

			triggerEvent($('.child').eq(1)[0], 'click');
			expect($('.child').eq(1)[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.child').eq(1)[0], 'mouseenter');
			expect($('.child').eq(1)[0].style.backgroundColor).to.equal('purple');

		});

		it('should inject the event and element into the callback', () => {
			$events.on('.test', 'click', (e, el) => {
				expect(el.className).to.equal('test');
				expect(e.type).to.equal('click');
			});

			triggerEvent($('.test')[0], 'click');
		});

		it('should bind multiple events to a single element selection', () => {
			$events.on('.test', {
				click() {
					$('.test')[0].style.backgroundColor = 'red';
				},
				mouseenter() {
					$('.test')[0].style.backgroundColor = 'purple';
				}
			});

			triggerEvent($('.test')[0], 'click');
			expect($('.test')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.test')[0], 'mouseenter');
			expect($('.test')[0].style.backgroundColor).to.equal('purple');
		})

		describe('once', () => {
			it('should bind an event that fires only once', () => {
				$events.on('.test', 'click', () => {
					let bgColor = $('.test')[0].style.backgroundColor;

					$('.test')[0].style.backgroundColor =
						bgColor === 'red' ? 'purple' : 'red';
				}, {
					once: true
				});

				triggerEvent($('.test')[0], 'click');
				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('targ', () => {
			// TODO: what does this do?
			it('targ', () => {
				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					targ: '.test'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});

			// TODO: get clarification
			it('should set ref on targ', () => {
				before(createSingleDiv);

				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red'
				}, {
					targ: 'ref:test'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('args', () => {

			it('can add injected arguments', () => {
				let state = false;

				$events.on('.test', 'click', (e, el, arg1, arg2) => {
					expect(arg1).to.equal('arg1');
					expect(arg2).to.equal('arg2');

					state = true;
				}, {
					args: ['arg1', 'arg2']
				});

				expect(state).to.equal(true);

				triggerEvent($('.test')[0], 'click');
			});
		});

		describe('scope', () => {
			it('can add change the scope of the callback', () => {
				let state = false;

				$events.on('.test', 'click', function() {
					expect(this.param).to.equal('test');
					state = true;
				}, {
					scope: {
						param: 'test'
					}
				});

				expect(state).to.equal(true);

				triggerEvent($('.test')[0], 'click');
			});
		});

		describe('delegate', () => {
			it('should delegate bound events to specified ancestor', () => {
				$events.on('.new-el', 'click', (e, el) => {
					el.style.backgroundColor = 'red';
				}, {
					delegate: 'body'
				});

				document.body.appendChild(createDiv({ className: 'new-el' }));

				triggerEvent($('.new-el')[0], 'click');
			});
		});

		describe('context', () => {
			it('should use provided context for selection', () => {
				// TODO: figure out the best way to test that it's actually
				// TODO: using provided context
				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					context: 'body'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('namespace', () => {
			it('should add a namespace to event', () => {
				// TODO: find the best way to test for namespace existence
				$events.on('.test', 'click', function() {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					namespace: 'namespace'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});
	});

	describe('trigger', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should trigger event for matching selection', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			$events.trigger('.test', 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});
	});

	describe('touch', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should bind touch event', () => {
			$events.on('.test', 'swipeLeft', () => {
				$('.test')[0].style.backgroundColor = 'red';
			}, {
				distance: 150,
				movement: 20
			});

			$events.trigger('.test', 'swipeLeft');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});
	});

	describe('bound', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('it should return an array of all bound events', () => {
			$events.on({
				'.test': {
					click() {
						return 'click';
					},
					mouseenter() {
						return 'mouseenter';
					}
				}
			});

			expect($events.bound()).to.be.an('array');
			expect($events.bound()[0]).to.be.an('object');
			expect($events.bound()[0].el.className).to.equal('test');
			expect($events.bound()[0].ev).to.equal('click');
			expect($events.bound()[0].evt).to.equal('click');
			expect($events.bound()[0].fn()).to.equal('click');

			expect($events.bound()[1].el.className).to.equal('test');
			expect($events.bound()[1].ev).to.equal('mouseenter');
			expect($events.bound()[1].evt).to.equal('mouseenter');
			expect($events.bound()[1].fn()).to.equal('mouseenter');
		});

		// TODO: finish this test
		// it('should check delegated selector against targeted selector', () => {
		// 	$events.on('ref:test', 'click', (e, el) => {
		// 		el.style.backgroundColor = 'red';
		// 	}, {
		// 		delegate: 'ref:test'
		// 	});
		//
		// 	createDiv({
		// 		className: 'new-el'
		// 	}, {
		// 		'data-ref': 'test'
		// 	}, true);
		//
		// 	triggerEvent($('ref:test')[0], 'click');
		// });
	});

	describe('off', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should remove a bound element', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off('.test');

			expect($events.bound().length).to.equal(0);
		});

		it('should remove a bound element by namespace', () => {
			$events.on('.test', 'click.namespace', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off(null, '.namespace');

			expect($events.bound().length).to.equal(0);
		});
	});

	describe('addEvent', () => {
		beforeEach(() => {
			createSingleDiv();
			createMultiDiv();
		});
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should register custom event', () => {
			$events.addEvent('pressHold', function(el, fn, conf) {
				$events.on(el, 'mousedown.pressHold', function(e, el) {
					expect(el.className).to.equal('test');
				}, conf);

				$events.on(el, 'mouseup.pressHold', function(e, el) {
					expect(el.className).to.equal('test');
				});
			}, function(el, fn) {
				$events.off(el, 'mouseup.pressHold', fn);
			});

			$events.on('.test', 'pressHold', function(e, el) {
				$('.test')[0].style.backgroundColor = 'red';
			});

			$events.trigger('.test', 'pressHold');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off('.test', null, (e) => {
				// TODO: Find a better way to test this
			});
		});
	});

	// TODO: finish this test - line 99
	// describe('init', () => {
	// 	beforeEach(createSingleDiv);
	// 	afterEach(resetDOM);
	//
	// 	it('should fire event immediately', () => {
	// 		$events.on('.test', 'click', () => {
	// 			$('.test')[0].style.backgroundColor = 'red';
	// 		}, {
	// 			init: true
	// 		});
	//
	// 		triggerEvent($('.test')[0], 'click');
	//
	// 		expect($('.test')[0].style.backgroundColor).to.equal('red');
	// 	});
	// });
});<|endoftext|>


<commit_before>import $ from 'wee-dom';
import $events from 'wee-events';
import { createDiv, createSingleDiv, createMultiDiv, resetDOM } from '../helpers/dom';

function removeEvents() {
	let elements = document.body.getElementsByTagName('*');

	for (let i = elements.length; i--;) {
		let oldElement = elements[i];
		let newElement = oldElement.cloneNode(true);

		oldElement.parentNode.replaceChild(newElement, oldElement);
	}

	$events.off();
}

function triggerEvent(el, type) {
	let e = document.createEvent('HTMLEvents');
	e.initEvent(type, false, true);
	el.dispatchEvent(e);
}

describe('Events', () => {
	describe('on', () => {
		beforeEach(() => {
			createSingleDiv();
			createMultiDiv();
		});
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should bind a single event to a single element', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});

		it('should bind multiple events to a single element', () => {
			$events.on({
				'.test': {
					click() {
						$('.test')[0].style.backgroundColor = 'red';
					},
					mouseenter() {
						$('.test')[0].style.backgroundColor = 'purple';
					}
				}
			});

			triggerEvent($('.test')[0], 'click');
			expect($('.test')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.test')[0], 'mouseenter');
			expect($('.test')[0].style.backgroundColor).to.equal('purple');
		});

		it('should bind multiple events to multiple elements', () => {
			$events.on({
				'#first': {
					click() {
						$('#first')[0].style.backgroundColor = 'red';
					},
					mouseenter() {
						$('#first')[0].style.backgroundColor = 'purple';
					}
				},
				'.other-class': {
					click() {
						$('.other-class')[0].style.backgroundColor = 'red';
					},
					mouseenter() {
						$('.other-class')[0].style.backgroundColor = 'purple';
					}
				}
			});

			triggerEvent($('#first')[0], 'click');
			expect($('#first')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('#first')[0], 'mouseenter');
			expect($('#first')[0].style.backgroundColor).to.equal('purple');
			triggerEvent($('.other-class')[0], 'click');
			expect($('.other-class')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.other-class')[0], 'mouseenter');
			expect($('.other-class')[0].style.backgroundColor).to.equal('purple');
		});

		it('should inject the event and element into the callback', () => {
			$events.on('.test', 'click', (e, el) => {
				expect(el.className).to.equal('test');
				expect(e.type).to.equal('click');
			});

			triggerEvent($('.test')[0], 'click');
		});

		it('should bind multiple events to a single element selection', () => {
			$events.on('.test', {
				click() {
					$('.test')[0].style.backgroundColor = 'red';
				},
				mouseenter() {
					$('.test')[0].style.backgroundColor = 'purple';
				}
			});

			triggerEvent($('.test')[0], 'click');
			expect($('.test')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.test')[0], 'mouseenter');
			expect($('.test')[0].style.backgroundColor).to.equal('purple');
		})

		describe('once', () => {
			it('should bind an event that fires only once', () => {
				$events.on('.test', 'click', () => {
					let bgColor = $('.test')[0].style.backgroundColor;

					$('.test')[0].style.backgroundColor =
						bgColor === 'red' ? 'purple' : 'red';
				}, {
					once: true
				});

				triggerEvent($('.test')[0], 'click');
				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('targ', () => {
			// TODO: what does this do?
			it('targ', () => {
				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					targ: '.test'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});

			// TODO: get clarification
			it('should set ref on targ', () => {
				before(createSingleDiv);

				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red'
				}, {
					targ: 'ref:test'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('args', () => {
			it('can add injected arguments', () => {
				$events.on('.test', 'click', (e, el, arg1, arg2) => {
					expect(arg1).to.equal('arg1');
					expect(arg2).to.equal('arg2');
				}, {
					args: ['arg1', 'arg2']
				});

				triggerEvent($('.test')[0], 'click');
			});
		});

		describe('scope', () => {
			it('can add change the scope of the callback', () => {
				let test = {
					param: 'test',
					bind() {
						$events.on('.test', 'click', function() {
							expect(this.param).to.equal('test');
						}, {
							scope: this
						});
					}
				}

				test.bind();

				triggerEvent($('.test')[0], 'click');
			});
		});

		describe('delegate', () => {
			it('should delegate bound events to specified ancestor', () => {
				$events.on('.new-el', 'click', (e, el) => {
					el.style.backgroundColor = 'red';
				}, {
					delegate: 'body'
				});

				document.body.appendChild(createDiv({ className: 'new-el' }));

				triggerEvent($('.new-el')[0], 'click');
			});
		});

		describe('context', () => {
			it('should use provided context for selection', () => {
				// TODO: figure out the best way to test that it's actually
				// TODO: using provided context
				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					context: 'body'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('namespace', () => {
			it('should add a namespace to event', () => {
				// TODO: find the best way to test for namespace existence
				$events.on('.test', 'click', function() {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					namespace: 'namespace'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});
	});

	describe('trigger', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should trigger event for matching selection', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			$events.trigger('.test', 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});
	});

	describe('touch', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should bind touch event', () => {
			$events.on('.test', 'swipeLeft', () => {
				$('.test')[0].style.backgroundColor = 'red';
			}, {
				distance: 150,
				movement: 20
			});

			$events.trigger('.test', 'swipeLeft');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});
	});

	describe('bound', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('it should return an array of all bound events', () => {
			$events.on({
				'.test': {
					click() {
						return 'click';
					},
					mouseenter() {
						return 'mouseenter';
					}
				}
			});

			expect($events.bound()).to.be.an('array');
			expect($events.bound()[0]).to.be.an('object');
			expect($events.bound()[0].el.className).to.equal('test');
			expect($events.bound()[0].ev).to.equal('click');
			expect($events.bound()[0].evt).to.equal('click');
			expect($events.bound()[0].fn()).to.equal('click');

			expect($events.bound()[1].el.className).to.equal('test');
			expect($events.bound()[1].ev).to.equal('mouseenter');
			expect($events.bound()[1].evt).to.equal('mouseenter');
			expect($events.bound()[1].fn()).to.equal('mouseenter');
		});
	});

	describe('off', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should remove a bound element', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off('.test');

			expect($events.bound().length).to.equal(0);
		});

		it('should remove a bound element by namespace', () => {
			$events.on('.test', 'click.namespace', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off(null, '.namespace');

			expect($events.bound().length).to.equal(0);
		});
	});

	describe('addEvent', () => {
		beforeEach(() => {
			createSingleDiv();
			createMultiDiv();
		});
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should register custom event', () => {
			$events.addEvent('pressHold', function(el, fn, conf) {
				$events.on(el, 'mousedown.pressHold', function(e, el) {
					expect(el.className).to.equal('test');
				}, conf);

				$events.on(el, 'mouseup.pressHold', function(e, el) {
					expect(el.className).to.equal('test');
				});
			}, function(el, fn) {
				$events.off(el, 'mouseup.pressHold', fn);
			});

			$events.on('.test', 'pressHold', function(e, el) {
				$('.test')[0].style.backgroundColor = 'red';
			});

			$events.trigger('.test', 'pressHold');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off('.test', null, (e) => {
				// TODO: Find a better way to test this
			});
		});
	});

	// TODO: finish this test - line 99
	// describe('init', () => {
	// 	beforeEach(createSingleDiv);
	// 	afterEach(resetDOM);
	//
	// 	it('should fire event immediately', () => {
	// 		$events.on('.test', 'click', () => {
	// 			$('.test')[0].style.backgroundColor = 'red';
	// 		}, {
	// 			init: true
	// 		});
	//
	// 		triggerEvent($('.test')[0], 'click');
	//
	// 		expect($('.test')[0].style.backgroundColor).to.equal('red');
	// 	});
	// });
});<commit_msg>Comment out unfinished test<commit_after>import $ from 'wee-dom';
import $events from 'wee-events';
import { createDiv, createSingleDiv, createMultiDiv, resetDOM } from '../helpers/dom';

function removeEvents() {
	let elements = document.body.getElementsByTagName('*');

	for (let i = elements.length; i--;) {
		let oldElement = elements[i];
		let newElement = oldElement.cloneNode(true);

		oldElement.parentNode.replaceChild(newElement, oldElement);
	}

	$events.off();
}

function triggerEvent(el, type) {
	let e = document.createEvent('HTMLEvents');
	e.initEvent(type, false, true);
	el.dispatchEvent(e);
}

describe('Events', () => {
	describe('on', () => {
		beforeEach(() => {
			createSingleDiv();
			createMultiDiv();
		});
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should bind a single event to a single element', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});

		it('should bind multiple events to a single element', () => {
			$events.on({
				'.test': {
					click() {
						$('.test')[0].style.backgroundColor = 'red';
					},
					mouseenter() {
						$('.test')[0].style.backgroundColor = 'purple';
					}
				}
			});

			triggerEvent($('.test')[0], 'click');
			expect($('.test')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.test')[0], 'mouseenter');
			expect($('.test')[0].style.backgroundColor).to.equal('purple');
		});

		it('should bind multiple events to multiple elements', () => {
			$events.on({
				'#first': {
					click() {
						$('#first')[0].style.backgroundColor = 'red';
					},
					mouseenter() {
						$('#first')[0].style.backgroundColor = 'purple';
					}
				},
				'.other-class': {
					click() {
						$('.other-class')[0].style.backgroundColor = 'red';
					},
					mouseenter() {
						$('.other-class')[0].style.backgroundColor = 'purple';
					}
				}
			});

			triggerEvent($('#first')[0], 'click');
			expect($('#first')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('#first')[0], 'mouseenter');
			expect($('#first')[0].style.backgroundColor).to.equal('purple');
			triggerEvent($('.other-class')[0], 'click');
			expect($('.other-class')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.other-class')[0], 'mouseenter');
			expect($('.other-class')[0].style.backgroundColor).to.equal('purple');
		});

		it('should inject the event and element into the callback', () => {
			$events.on('.test', 'click', (e, el) => {
				expect(el.className).to.equal('test');
				expect(e.type).to.equal('click');
			});

			triggerEvent($('.test')[0], 'click');
		});

		it('should bind multiple events to a single element selection', () => {
			$events.on('.test', {
				click() {
					$('.test')[0].style.backgroundColor = 'red';
				},
				mouseenter() {
					$('.test')[0].style.backgroundColor = 'purple';
				}
			});

			triggerEvent($('.test')[0], 'click');
			expect($('.test')[0].style.backgroundColor).to.equal('red');
			triggerEvent($('.test')[0], 'mouseenter');
			expect($('.test')[0].style.backgroundColor).to.equal('purple');
		})

		describe('once', () => {
			it('should bind an event that fires only once', () => {
				$events.on('.test', 'click', () => {
					let bgColor = $('.test')[0].style.backgroundColor;

					$('.test')[0].style.backgroundColor =
						bgColor === 'red' ? 'purple' : 'red';
				}, {
					once: true
				});

				triggerEvent($('.test')[0], 'click');
				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('targ', () => {
			// TODO: what does this do?
			it('targ', () => {
				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					targ: '.test'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});

			// TODO: get clarification
			it('should set ref on targ', () => {
				before(createSingleDiv);

				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red'
				}, {
					targ: 'ref:test'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('args', () => {
			it('can add injected arguments', () => {
				$events.on('.test', 'click', (e, el, arg1, arg2) => {
					expect(arg1).to.equal('arg1');
					expect(arg2).to.equal('arg2');
				}, {
					args: ['arg1', 'arg2']
				});

				triggerEvent($('.test')[0], 'click');
			});
		});

		describe('scope', () => {
			it('can add change the scope of the callback', () => {
				let test = {
					param: 'test',
					bind() {
						$events.on('.test', 'click', function() {
							expect(this.param).to.equal('test');
						}, {
							scope: this
						});
					}
				}

				test.bind();

				triggerEvent($('.test')[0], 'click');
			});
		});

		describe('delegate', () => {
			it('should delegate bound events to specified ancestor', () => {
				$events.on('.new-el', 'click', (e, el) => {
					el.style.backgroundColor = 'red';
				}, {
					delegate: 'body'
				});

				document.body.appendChild(createDiv({ className: 'new-el' }));

				triggerEvent($('.new-el')[0], 'click');
			});
		});

		describe('context', () => {
			it('should use provided context for selection', () => {
				// TODO: figure out the best way to test that it's actually
				// TODO: using provided context
				$events.on('.test', 'click', () => {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					context: 'body'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});

		describe('namespace', () => {
			it('should add a namespace to event', () => {
				// TODO: find the best way to test for namespace existence
				$events.on('.test', 'click', function() {
					$('.test')[0].style.backgroundColor = 'red';
				}, {
					namespace: 'namespace'
				});

				triggerEvent($('.test')[0], 'click');

				expect($('.test')[0].style.backgroundColor).to.equal('red');
			});
		});
	});

	describe('trigger', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should trigger event for matching selection', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			$events.trigger('.test', 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});
	});

	describe('touch', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should bind touch event', () => {
			$events.on('.test', 'swipeLeft', () => {
				$('.test')[0].style.backgroundColor = 'red';
			}, {
				distance: 150,
				movement: 20
			});

			$events.trigger('.test', 'swipeLeft');

			expect($('.test')[0].style.backgroundColor).to.equal('red');
		});
	});

	describe('bound', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('it should return an array of all bound events', () => {
			$events.on({
				'.test': {
					click() {
						return 'click';
					},
					mouseenter() {
						return 'mouseenter';
					}
				}
			});

			expect($events.bound()).to.be.an('array');
			expect($events.bound()[0]).to.be.an('object');
			expect($events.bound()[0].el.className).to.equal('test');
			expect($events.bound()[0].ev).to.equal('click');
			expect($events.bound()[0].evt).to.equal('click');
			expect($events.bound()[0].fn()).to.equal('click');

			expect($events.bound()[1].el.className).to.equal('test');
			expect($events.bound()[1].ev).to.equal('mouseenter');
			expect($events.bound()[1].evt).to.equal('mouseenter');
			expect($events.bound()[1].fn()).to.equal('mouseenter');
		});

		// TODO: finish this test
		// it('should check delegated selector against targeted selector', () => {
		// 	$events.on('ref:test', 'click', (e, el) => {
		// 		el.style.backgroundColor = 'red';
		// 	}, {
		// 		delegate: 'ref:test'
		// 	});
		//
		// 	createDiv({
		// 		className: 'new-el'
		// 	}, {
		// 		'data-ref': 'test'
		// 	}, true);
		//
		// 	triggerEvent($('ref:test')[0], 'click');
		// });
	});

	describe('off', () => {
		beforeEach(createSingleDiv);
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should remove a bound element', () => {
			$events.on('.test', 'click', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off('.test');

			expect($events.bound().length).to.equal(0);
		});

		it('should remove a bound element by namespace', () => {
			$events.on('.test', 'click.namespace', () => {
				$('.test')[0].style.backgroundColor = 'red';
			});

			triggerEvent($('.test')[0], 'click');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off(null, '.namespace');

			expect($events.bound().length).to.equal(0);
		});
	});

	describe('addEvent', () => {
		beforeEach(() => {
			createSingleDiv();
			createMultiDiv();
		});
		afterEach(() => {
			resetDOM();
			removeEvents();
		});

		it('should register custom event', () => {
			$events.addEvent('pressHold', function(el, fn, conf) {
				$events.on(el, 'mousedown.pressHold', function(e, el) {
					expect(el.className).to.equal('test');
				}, conf);

				$events.on(el, 'mouseup.pressHold', function(e, el) {
					expect(el.className).to.equal('test');
				});
			}, function(el, fn) {
				$events.off(el, 'mouseup.pressHold', fn);
			});

			$events.on('.test', 'pressHold', function(e, el) {
				$('.test')[0].style.backgroundColor = 'red';
			});

			$events.trigger('.test', 'pressHold');

			expect($('.test')[0].style.backgroundColor).to.equal('red');

			$events.off('.test', null, (e) => {
				// TODO: Find a better way to test this
			});
		});
	});

	// TODO: finish this test - line 99
	// describe('init', () => {
	// 	beforeEach(createSingleDiv);
	// 	afterEach(resetDOM);
	//
	// 	it('should fire event immediately', () => {
	// 		$events.on('.test', 'click', () => {
	// 			$('.test')[0].style.backgroundColor = 'red';
	// 		}, {
	// 			init: true
	// 		});
	//
	// 		triggerEvent($('.test')[0], 'click');
	//
	// 		expect($('.test')[0].style.backgroundColor).to.equal('red');
	// 	});
	// });
});<|endoftext|>