How to use unknownOption method in Cypress

Best JavaScript code snippet using cypress

select.js

Source:select.js Github

copy

Full Screen

1'use strict';2var ngOptionsMinErr = minErr('ngOptions');3/**4 * @ngdoc directive5 * @name select6 * @restrict E7 *8 * @description9 * HTML `SELECT` element with angular data-binding.10 *11 * # `ngOptions`12 *13 * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`14 * elements for the `<select>` element using the array or object obtained by evaluating the15 * `ngOptions` comprehension_expression.16 *17 * When an item in the `<select>` menu is selected, the array element or object property18 * represented by the selected option will be bound to the model identified by the `ngModel`19 * directive.20 *21 * <div class="alert alert-warning">22 * **Note:** `ngModel` compares by reference, not value. This is important when binding to an23 * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).24 * </div>25 *26 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can27 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"28 * option. See example below for demonstration.29 *30 * <div class="alert alert-warning">31 * **Note:** `ngOptions` provides an iterator facility for the `<option>` element which should be used instead32 * of {@link ng.directive:ngRepeat ngRepeat} when you want the33 * `select` model to be bound to a non-string value. This is because an option element can only34 * be bound to string values at present.35 * </div>36 *37 * @param {string} ngModel Assignable angular expression to data-bind to.38 * @param {string=} name Property name of the form under which the control is published.39 * @param {string=} required The control is considered valid only if value is entered.40 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to41 *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of42 *    `required` when you want to data-bind to the `required` attribute.43 * @param {comprehension_expression=} ngOptions in one of the following forms:44 *45 *   * for array data sources:46 *     * `label` **`for`** `value` **`in`** `array`47 *     * `select` **`as`** `label` **`for`** `value` **`in`** `array`48 *     * `label`  **`group by`** `group` **`for`** `value` **`in`** `array`49 *     * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`50 *   * for object data sources:51 *     * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`52 *     * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`53 *     * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`54 *     * `select` **`as`** `label` **`group by`** `group`55 *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`56 *57 * Where:58 *59 *   * `array` / `object`: an expression which evaluates to an array / object to iterate over.60 *   * `value`: local variable which will refer to each item in the `array` or each property value61 *      of `object` during iteration.62 *   * `key`: local variable which will refer to a property name in `object` during iteration.63 *   * `label`: The result of this expression will be the label for `<option>` element. The64 *     `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).65 *   * `select`: The result of this expression will be bound to the model of the parent `<select>`66 *      element. If not specified, `select` expression will default to `value`.67 *   * `group`: The result of this expression will be used to group options using the `<optgroup>`68 *      DOM element.69 *   * `trackexpr`: Used when working with an array of objects. The result of this expression will be70 *      used to identify the objects in the array. The `trackexpr` will most likely refer to the71 *     `value` variable (e.g. `value.propertyName`).72 *73 * @example74    <example>75      <file name="index.html">76        <script>77        function MyCntrl($scope) {78          $scope.colors = [79            {name:'black', shade:'dark'},80            {name:'white', shade:'light'},81            {name:'red', shade:'dark'},82            {name:'blue', shade:'dark'},83            {name:'yellow', shade:'light'}84          ];85          $scope.myColor = $scope.colors[2]; // red86        }87        </script>88        <div ng-controller="MyCntrl">89          <ul>90            <li ng-repeat="color in colors">91              Name: <input ng-model="color.name">92              [<a href ng-click="colors.splice($index, 1)">X</a>]93            </li>94            <li>95              [<a href ng-click="colors.push({})">add</a>]96            </li>97          </ul>98          <hr/>99          Color (null not allowed):100          <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>101          Color (null allowed):102          <span  class="nullable">103            <select ng-model="myColor" ng-options="color.name for color in colors">104              <option value="">-- choose color --</option>105            </select>106          </span><br/>107          Color grouped by shade:108          <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">109          </select><br/>110          Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>111          <hr/>112          Currently selected: {{ {selected_color:myColor}  }}113          <div style="border:solid 1px black; height:20px"114               ng-style="{'background-color':myColor.name}">115          </div>116        </div>117      </file>118      <file name="protractor.js" type="protractor">119         it('should check ng-options', function() {120           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');121           element.all(by.select('myColor')).first().click();122           element.all(by.css('select[ng-model="myColor"] option')).first().click();123           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');124           element(by.css('.nullable select[ng-model="myColor"]')).click();125           element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();126           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');127         });128      </file>129    </example>130 */131var ngOptionsDirective = valueFn({ terminal: true });132// jshint maxlen: false133var selectDirective = ['$compile', '$parse', function($compile,   $parse) {134                         //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888135  var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/,136      nullModelCtrl = {$setViewValue: noop};137// jshint maxlen: 100138  return {139    restrict: 'E',140    require: ['select', '?ngModel'],141    controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {142      var self = this,143          optionsMap = {},144          ngModelCtrl = nullModelCtrl,145          nullOption,146          unknownOption;147      self.databound = $attrs.ngModel;148      self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {149        ngModelCtrl = ngModelCtrl_;150        nullOption = nullOption_;151        unknownOption = unknownOption_;152      };153      self.addOption = function(value) {154        assertNotHasOwnProperty(value, '"option value"');155        optionsMap[value] = true;156        if (ngModelCtrl.$viewValue == value) {157          $element.val(value);158          if (unknownOption.parent()) unknownOption.remove();159        }160      };161      self.removeOption = function(value) {162        if (this.hasOption(value)) {163          delete optionsMap[value];164          if (ngModelCtrl.$viewValue == value) {165            this.renderUnknownOption(value);166          }167        }168      };169      self.renderUnknownOption = function(val) {170        var unknownVal = '? ' + hashKey(val) + ' ?';171        unknownOption.val(unknownVal);172        $element.prepend(unknownOption);173        $element.val(unknownVal);174        unknownOption.prop('selected', true); // needed for IE175      };176      self.hasOption = function(value) {177        return optionsMap.hasOwnProperty(value);178      };179      $scope.$on('$destroy', function() {180        // disable unknown option so that we don't do work when the whole select is being destroyed181        self.renderUnknownOption = noop;182      });183    }],184    link: function(scope, element, attr, ctrls) {185      // if ngModel is not defined, we don't need to do anything186      if (!ctrls[1]) return;187      var selectCtrl = ctrls[0],188          ngModelCtrl = ctrls[1],189          multiple = attr.multiple,190          optionsExp = attr.ngOptions,191          nullOption = false, // if false, user will not be able to select it (used by ngOptions)192          emptyOption,193          // we can't just jqLite('<option>') since jqLite is not smart enough194          // to create it in <select> and IE barfs otherwise.195          optionTemplate = jqLite(document.createElement('option')),196          optGroupTemplate =jqLite(document.createElement('optgroup')),197          unknownOption = optionTemplate.clone();198      // find "null" option199      for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {200        if (children[i].value === '') {201          emptyOption = nullOption = children.eq(i);202          break;203        }204      }205      selectCtrl.init(ngModelCtrl, nullOption, unknownOption);206      // required validator207      if (multiple) {208        ngModelCtrl.$isEmpty = function(value) {209          return !value || value.length === 0;210        };211      }212      if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);213      else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);214      else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);215      ////////////////////////////216      function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {217        ngModelCtrl.$render = function() {218          var viewValue = ngModelCtrl.$viewValue;219          if (selectCtrl.hasOption(viewValue)) {220            if (unknownOption.parent()) unknownOption.remove();221            selectElement.val(viewValue);222            if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy223          } else {224            if (isUndefined(viewValue) && emptyOption) {225              selectElement.val('');226            } else {227              selectCtrl.renderUnknownOption(viewValue);228            }229          }230        };231        selectElement.on('change', function() {232          scope.$apply(function() {233            if (unknownOption.parent()) unknownOption.remove();234            ngModelCtrl.$setViewValue(selectElement.val());235          });236        });237      }238      function setupAsMultiple(scope, selectElement, ctrl) {239        var lastView;240        ctrl.$render = function() {241          var items = new HashMap(ctrl.$viewValue);242          forEach(selectElement.find('option'), function(option) {243            option.selected = isDefined(items.get(option.value));244          });245        };246        // we have to do it on each watch since ngModel watches reference, but247        // we need to work of an array, so we need to see if anything was inserted/removed248        scope.$watch(function selectMultipleWatch() {249          if (!equals(lastView, ctrl.$viewValue)) {250            lastView = shallowCopy(ctrl.$viewValue);251            ctrl.$render();252          }253        });254        selectElement.on('change', function() {255          scope.$apply(function() {256            var array = [];257            forEach(selectElement.find('option'), function(option) {258              if (option.selected) {259                array.push(option.value);260              }261            });262            ctrl.$setViewValue(array);263          });264        });265      }266      function setupAsOptions(scope, selectElement, ctrl) {267        var match;268        if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {269          throw ngOptionsMinErr('iexp',270            "Expected expression in form of " +271            "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +272            " but got '{0}'. Element: {1}",273            optionsExp, startingTag(selectElement));274        }275        var displayFn = $parse(match[2] || match[1]),276            valueName = match[4] || match[6],277            keyName = match[5],278            groupByFn = $parse(match[3] || ''),279            valueFn = $parse(match[2] ? match[1] : valueName),280            valuesFn = $parse(match[7]),281            track = match[8],282            trackFn = track ? $parse(match[8]) : null,283            // This is an array of array of existing option groups in DOM.284            // We try to reuse these if possible285            // - optionGroupsCache[0] is the options with no option group286            // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element287            optionGroupsCache = [[{element: selectElement, label:''}]];288        if (nullOption) {289          // compile the element since there might be bindings in it290          $compile(nullOption)(scope);291          // remove the class, which is added automatically because we recompile the element and it292          // becomes the compilation root293          nullOption.removeClass('ng-scope');294          // we need to remove it before calling selectElement.empty() because otherwise IE will295          // remove the label from the element. wtf?296          nullOption.remove();297        }298        // clear contents, we'll add what's needed based on the model299        selectElement.empty();300        selectElement.on('change', function() {301          scope.$apply(function() {302            var optionGroup,303                collection = valuesFn(scope) || [],304                locals = {},305                key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;306            if (multiple) {307              value = [];308              for (groupIndex = 0, groupLength = optionGroupsCache.length;309                   groupIndex < groupLength;310                   groupIndex++) {311                // list of options for that group. (first item has the parent)312                optionGroup = optionGroupsCache[groupIndex];313                for(index = 1, length = optionGroup.length; index < length; index++) {314                  if ((optionElement = optionGroup[index].element)[0].selected) {315                    key = optionElement.val();316                    if (keyName) locals[keyName] = key;317                    if (trackFn) {318                      for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {319                        locals[valueName] = collection[trackIndex];320                        if (trackFn(scope, locals) == key) break;321                      }322                    } else {323                      locals[valueName] = collection[key];324                    }325                    value.push(valueFn(scope, locals));326                  }327                }328              }329            } else {330              key = selectElement.val();331              if (key == '?') {332                value = undefined;333              } else if (key === ''){334                value = null;335              } else {336                if (trackFn) {337                  for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {338                    locals[valueName] = collection[trackIndex];339                    if (trackFn(scope, locals) == key) {340                      value = valueFn(scope, locals);341                      break;342                    }343                  }344                } else {345                  locals[valueName] = collection[key];346                  if (keyName) locals[keyName] = key;347                  value = valueFn(scope, locals);348                }349              }350              // Update the null option's selected property here so $render cleans it up correctly351              if (optionGroupsCache[0].length > 1) {352                if (optionGroupsCache[0][1].id !== key) {353                  optionGroupsCache[0][1].selected = false;354                }355              }356            }357            ctrl.$setViewValue(value);358          });359        });360        ctrl.$render = render;361        // TODO(vojta): can't we optimize this ?362        scope.$watch(render);363        function render() {364              // Temporary location for the option groups before we render them365          var optionGroups = {'':[]},366              optionGroupNames = [''],367              optionGroupName,368              optionGroup,369              option,370              existingParent, existingOptions, existingOption,371              modelValue = ctrl.$modelValue,372              values = valuesFn(scope) || [],373              keys = keyName ? sortedKeys(values) : values,374              key,375              groupLength, length,376              groupIndex, index,377              locals = {},378              selected,379              selectedSet = false, // nothing is selected yet380              lastElement,381              element,382              label;383          if (multiple) {384            if (trackFn && isArray(modelValue)) {385              selectedSet = new HashMap([]);386              for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {387                locals[valueName] = modelValue[trackIndex];388                selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);389              }390            } else {391              selectedSet = new HashMap(modelValue);392            }393          }394          // We now build up the list of options we need (we merge later)395          for (index = 0; length = keys.length, index < length; index++) {396            key = index;397            if (keyName) {398              key = keys[index];399              if ( key.charAt(0) === '$' ) continue;400              locals[keyName] = key;401            }402            locals[valueName] = values[key];403            optionGroupName = groupByFn(scope, locals) || '';404            if (!(optionGroup = optionGroups[optionGroupName])) {405              optionGroup = optionGroups[optionGroupName] = [];406              optionGroupNames.push(optionGroupName);407            }408            if (multiple) {409              selected = isDefined(410                selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals))411              );412            } else {413              if (trackFn) {414                var modelCast = {};415                modelCast[valueName] = modelValue;416                selected = trackFn(scope, modelCast) === trackFn(scope, locals);417              } else {418                selected = modelValue === valueFn(scope, locals);419              }420              selectedSet = selectedSet || selected; // see if at least one item is selected421            }422            label = displayFn(scope, locals); // what will be seen by the user423            // doing displayFn(scope, locals) || '' overwrites zero values424            label = isDefined(label) ? label : '';425            optionGroup.push({426              // either the index into array or key from object427              id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index),428              label: label,429              selected: selected                   // determine if we should be selected430            });431          }432          if (!multiple) {433            if (nullOption || modelValue === null) {434              // insert null option if we have a placeholder, or the model is null435              optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});436            } else if (!selectedSet) {437              // option could not be found, we have to insert the undefined item438              optionGroups[''].unshift({id:'?', label:'', selected:true});439            }440          }441          // Now we need to update the list of DOM nodes to match the optionGroups we computed above442          for (groupIndex = 0, groupLength = optionGroupNames.length;443               groupIndex < groupLength;444               groupIndex++) {445            // current option group name or '' if no group446            optionGroupName = optionGroupNames[groupIndex];447            // list of options for that group. (first item has the parent)448            optionGroup = optionGroups[optionGroupName];449            if (optionGroupsCache.length <= groupIndex) {450              // we need to grow the optionGroups451              existingParent = {452                element: optGroupTemplate.clone().attr('label', optionGroupName),453                label: optionGroup.label454              };455              existingOptions = [existingParent];456              optionGroupsCache.push(existingOptions);457              selectElement.append(existingParent.element);458            } else {459              existingOptions = optionGroupsCache[groupIndex];460              existingParent = existingOptions[0];  // either SELECT (no group) or OPTGROUP element461              // update the OPTGROUP label if not the same.462              if (existingParent.label != optionGroupName) {463                existingParent.element.attr('label', existingParent.label = optionGroupName);464              }465            }466            lastElement = null;  // start at the beginning467            for(index = 0, length = optionGroup.length; index < length; index++) {468              option = optionGroup[index];469              if ((existingOption = existingOptions[index+1])) {470                // reuse elements471                lastElement = existingOption.element;472                if (existingOption.label !== option.label) {473                  lastElement.text(existingOption.label = option.label);474                }475                if (existingOption.id !== option.id) {476                  lastElement.val(existingOption.id = option.id);477                }478                // lastElement.prop('selected') provided by jQuery has side-effects479                if (existingOption.selected !== option.selected) {480                  lastElement.prop('selected', (existingOption.selected = option.selected));481                }482              } else {483                // grow elements484                // if it's a null option485                if (option.id === '' && nullOption) {486                  // put back the pre-compiled element487                  element = nullOption;488                } else {489                  // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but490                  // in this version of jQuery on some browser the .text() returns a string491                  // rather then the element.492                  (element = optionTemplate.clone())493                      .val(option.id)494                      .attr('selected', option.selected)495                      .text(option.label);496                }497                existingOptions.push(existingOption = {498                    element: element,499                    label: option.label,500                    id: option.id,501                    selected: option.selected502                });503                if (lastElement) {504                  lastElement.after(element);505                } else {506                  existingParent.element.append(element);507                }508                lastElement = element;509              }510            }511            // remove any excessive OPTIONs in a group512            index++; // increment since the existingOptions[0] is parent element not OPTION513            while(existingOptions.length > index) {514              existingOptions.pop().element.remove();515            }516          }517          // remove any excessive OPTGROUPs from select518          while(optionGroupsCache.length > groupIndex) {519            optionGroupsCache.pop()[0].element.remove();520          }521        }522      }523    }524  };525}];526var optionDirective = ['$interpolate', function($interpolate) {527  var nullSelectCtrl = {528    addOption: noop,529    removeOption: noop530  };531  return {532    restrict: 'E',533    priority: 100,534    compile: function(element, attr) {535      if (isUndefined(attr.value)) {536        var interpolateFn = $interpolate(element.text(), true);537        if (!interpolateFn) {538          attr.$set('value', element.text());539        }540      }541      return function (scope, element, attr) {542        var selectCtrlName = '$selectController',543            parent = element.parent(),544            selectCtrl = parent.data(selectCtrlName) ||545              parent.parent().data(selectCtrlName); // in case we are in optgroup546        if (selectCtrl && selectCtrl.databound) {547          // For some reason Opera defaults to true and if not overridden this messes up the repeater.548          // We don't want the view to drive the initialization of the model anyway.549          element.prop('selected', false);550        } else {551          selectCtrl = nullSelectCtrl;552        }553        if (interpolateFn) {554          scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {555            attr.$set('value', newVal);556            if (newVal !== oldVal) selectCtrl.removeOption(oldVal);557            selectCtrl.addOption(newVal);558          });559        } else {560          selectCtrl.addOption(attr.value);561        }562        element.on('$destroy', function() {563          selectCtrl.removeOption(attr.value);564        });565      };566    }567  };...

Full Screen

Full Screen

sails.js

Source:sails.js Github

copy

Full Screen

1#!/usr/bin/env node2/**3 * Module dependencies4 */5var _ = require('@sailshq/lodash');6var program = require('./private/patched-commander');7var sailsPackageJson = require('../package.json');8var NOOP = function() {};9program10  .version(sailsPackageJson.version, '-v, --version');11//12// Normalize version argument, i.e.13//14// $ sails -v15// $ sails -V16// $ sails --version17// $ sails version18//19// make `-v` option case-insensitive20process.argv = _.map(process.argv, function(arg) {21  return (arg === '-V') ? '-v' : arg;22});23// $ sails version (--version synonym)24program25  .command('version')26  .description('')27  .action(program.versionInformation);28program29  .unknownOption = NOOP;30program.usage('[command]');31// $ sails lift32var cmd;33cmd = program.command('lift');34cmd.option('--prod', 'Lift in "production" environment.');35cmd.option('--staging', 'Lift in "staging" environment.');36cmd.option('--port [port]', 'Listen on the specified port (defaults to 1337).');37cmd.option('--silent', 'Set log level to "silent".');38cmd.option('--verbose', 'Set log level to "verbose".');39cmd.option('--silly', 'Set log level to "silly".');40cmd.unknownOption = NOOP;41cmd.description('');42cmd.alias('l');43cmd.action(require('./sails-lift'));44// $ sails new <appname>45cmd = program.command('new [path_to_new_app]');46// cmd.option('--dry');47cmd.option('--no-front-end', 'Don\'t generate "assets", "views" or "task" folders.');48cmd.option('--fast', 'Don\'t install node modules after generating app.');49cmd.usage('[path_to_new_app]');50cmd.unknownOption = NOOP;51cmd.description('');52cmd.action(require('./sails-new'));53// $ sails generate <module>54cmd = program.command('generate');55// cmd.option('--dry');56cmd.unknownOption = NOOP;57cmd.description('');58cmd.usage('[something]');59cmd.action(require('./sails-generate'));60// $ sails upgrade61cmd = program.command('upgrade');62cmd.unknownOption = NOOP;63cmd.description('');64cmd.action(require('./sails-upgrade'));65// $ sails console66cmd = program.command('console');67cmd.option('--silent', 'Set log level to "silent".');68cmd.option('--verbose', 'Set log level to "silent".');69cmd.option('--silly', 'Set log level to "silly".');70cmd.option('--dontLift', 'Start console session without lifting an HTTP server.');71cmd.unknownOption = NOOP;72cmd.description('');73cmd.alias('c');74cmd.action(require('./sails-console'));75// $ sails www76// Compile `assets` directory into a standalone `www` folder.77cmd = program.command('www');78cmd.unknownOption = NOOP;79cmd.description('');80cmd.action(require('./sails-www'));81// $ sails debug82cmd = program.command('debug');83cmd.unknownOption = NOOP;84cmd.description('(for Node v5 and below)');85cmd.action(require('./sails-debug'));86// $ sails inspect87cmd = program.command('inspect');88cmd.unknownOption = NOOP;89cmd.description('(for Node v6 and above)');90cmd.action(require('./sails-inspect'));91// $ sails run92cmd = program.command('run');93cmd.usage('[name-of-script]');94cmd.unknownOption = NOOP;95cmd.description('');96cmd.action(require('./sails-run'));97// $ sails test98cmd = program.command('test');99cmd.unknownOption = NOOP;100cmd.description('');101cmd.action(function(){102  require('./sails-run')('test', _.last(arguments));103});104// $ sails lint105cmd = program.command('lint');106cmd.unknownOption = NOOP;107cmd.description('');108cmd.action(function(){109  require('./sails-run')('lint', _.last(arguments));110});111// - - - - - - - - - - - - - - - - - - - - - - - - - - -112// $ sails deploy113cmd = program.command('deploy');114// cmd.option('--dry');115cmd.unknownOption = NOOP;116cmd.description('');117cmd.usage('');118cmd.action(require('./sails-deploy'));119// FUTURE: ^^ Consider simplifying this into a script.120// - - - - - - - - - - - - - - - - - - - - - - - - - - -121// $ sails debug-console122cmd = program.command('debug-console');123cmd.unknownOption = NOOP;124cmd.description('');125cmd.alias('dc');126cmd.action(require('./sails-debug-console'));127//128// Normalize help argument, i.e.129//130// $ sails --help131// $ sails help132// $ sails133// $ sails <unrecognized_cmd>134//135// $ sails help (--help synonym)136cmd = program.command('help [command]');137cmd.description('');138cmd.action(function(){139  if (program.args.length > 1 && _.isString(program.args[0])) {140    var helpCmd = _.find(program.commands, {_name: program.args[0]});141    if (helpCmd) {142      helpCmd.help();143      return;144    }145  }146  program.help();147});148// $ sails <unrecognized_cmd>149// Output Sails help when an unrecognized command is used.150program151  .command('*')152  .action(function(cmd){153    console.log('\n  ** Unrecognized command:', cmd, '**');154    program.help();155  });156// Don't balk at unknown options157program.unknownOption = NOOP;158// $ sails159//160var millisecondsToWait = 5000;161setTimeout(function() {162    // Whatever you want to do after the wait163}, millisecondsToWait);164program.parse(process.argv);165var NO_COMMAND_SPECIFIED = program.args.length === 0;166if (NO_COMMAND_SPECIFIED) {167  program.help();...

Full Screen

Full Screen

strapi.js

Source:strapi.js Github

copy

Full Screen

1#!/usr/bin/env node2'use strict';3/**4 * Module dependencies5 */6// Public node modules.7const _ = require('lodash');8// Local Strapi dependencies.9const program = require('./_commander');10const packageJSON = require('../package.json');11// Needed.12const NOOP = function () {};13let cmd;14/**15 * Normalize version argument16 *17 * `$ strapi -v`18 * `$ strapi -V`19 * `$ strapi --version`20 * `$ strapi version`21 */22// Expose version.23program.version(packageJSON.version, '-v, --version');24// Make `-v` option case-insensitive.25process.argv = _.map(process.argv, function (arg) {26  return (arg === '-V') ? '-v' : arg;27});28// `$ strapi version` (--version synonym)29cmd = program.command('version');30cmd.description('output your version of Strapi');31cmd.action(program.versionInformation);32// `$ strapi new <name>`33cmd = program.command('new');34cmd.unknownOption = NOOP;35cmd.description('create a new application ');36cmd.action(require('./strapi-new'));37cmd.option('-d, --dry', 'naked Strapi application');38// `$ strapi start`39cmd = program.command('start');40cmd.unknownOption = NOOP;41cmd.description('start your Strapi application');42cmd.action(require('./strapi-start'));43// `$ strapi generate <generatorName>`44cmd = program.command('generate');45cmd.unknownOption = NOOP;46cmd.description('generate templates from a generator');47cmd.action(require('./strapi-generate'));48// `$ strapi console`49cmd = program.command('console');50cmd.unknownOption = NOOP;51cmd.description('open the Strapi framework console');52cmd.action(require('./strapi-console'));53// `$ strapi link`54cmd = program.command('link');55cmd.unknownOption = NOOP;56cmd.description('link an existing application to the Strapi Studio');57cmd.action(require('./strapi-link'));58// `$ strapi config`59cmd = program.command('config');60cmd.unknownOption = NOOP;61cmd.description('extend the Strapi framework with custom generators');62cmd.action(require('./strapi-config'));63// `$ strapi update`64cmd = program.command('update');65cmd.unknownOption = NOOP;66cmd.description('pull the latest updates of your custom generators');67cmd.action(require('./strapi-update'));68// `$ strapi login`69cmd = program.command('login');70cmd.unknownOption = NOOP;71cmd.description('connect your account to the Strapi Studio');72cmd.action(require('./strapi-login'));73// `$ strapi logout`74cmd = program.command('logout');75cmd.unknownOption = NOOP;76cmd.description('logout your account from the Strapi Studio');77cmd.action(require('./strapi-logout'));78/**79 * Normalize help argument80 */81// `$ strapi help` (--help synonym)82cmd = program.command('help');83cmd.description('output the help');84cmd.action(program.usageMinusWildcard);85// `$ strapi <unrecognized_cmd>`86// Mask the '*' in `help`.87cmd = program.command('*');88cmd.action(program.usageMinusWildcard);89// Don't balk at unknown options.90program.unknownOption = NOOP;91/**92 * `$ strapi`93 */94program.parse(process.argv);95const NO_COMMAND_SPECIFIED = program.args.length === 0;96if (NO_COMMAND_SPECIFIED) {97  program.usageMinusWildcard();...

Full Screen

Full Screen

extensio.js

Source:extensio.js Github

copy

Full Screen

1#!/usr/bin/env node2/**3 * Module dependencies4 */5// Node.js core.6var exec = require('child_process').exec;7// Public node modules.8var _ = require('lodash');9// Local dependencies.10var program = require('./_commander');11var package = require('../package.json');12// Needed.13var NOOP = function () {};14var cmd;15/**16 * Normalize version argument17 *18 * `$ extens.io -v`19 * `$ extens.io -V`20 * `$ extens.io --version`21 * `$ extens.io version`22 */23// Expose version.24program25  .version(package.version, '-v, --version');26// Make `-v` option case-insensitive.27process.argv = _.map(process.argv, function (arg) {28  return (arg === '-V') ? '-v' : arg;29});30// Common options.31program32  .option('--silent', 'without any logs')33  .option('--verbose', 'with debug logs')34  .option('--silly', 'with silly logs')35  .usage('[command]')36  .unknownOption = NOOP;37// `$ extens.io version` (--version synonym)38cmd = program.command('version');39cmd.description('output your version of extens.io.')40cmd.action(program.versionInformation);41// `$ extens.io lift`42cmd = program.command('lift');43cmd.option('--prod', 'lift your Sails application in a production environment');44cmd.option('--port [port]', 'lift your Sails application using a specific port');45cmd.unknownOption = NOOP;46cmd.description('lift your Sails server');47cmd.action(require('./extensio-lift'));48// `$ extens.io new <name>`49cmd = program.command('new [pathToNewApp]');50cmd.unknownOption = NOOP;51cmd.description('create a new application ');52cmd.usage('[pathToNewApp]');53cmd.action(require('./extensio-new'));54// `$ extens.io generate <generatorName>`55cmd = program.command('generate');56cmd.unknownOption = NOOP;57cmd.description('generate something using the extens.io CLI');58cmd.usage('[something] like `new`, `api`, `module`, `plugin`, etc.');59cmd.action(require('./extensio-generate'));60// `$ extens.io console`61cmd = program.command('console');62cmd.unknownOption = NOOP;63cmd.description('open the Sails console');64cmd.action(require('./extensio-console'));65// `$ extens.io debug`66cmd = program.command('debug');67cmd.unknownOption = NOOP;68cmd.description('run debugger');69cmd.action(require('./extensio-debug'));70/**71 * Normalize help argument72 *73 * `$ extens.io --help`74 * `$ extens.io help`75 * `$ extens.io`76 * `$ extens.io <unrecognized_cmd>`77 */78// `$ extens.io help` (--help synonym)79cmd = program.command('help');80cmd.description('output the help');81cmd.action(program.usageMinusWildcard);82// `$ extens.io <unrecognized_cmd>`83// Mask the '*' in `help`.84cmd = program.command('*');85cmd.action(program.usageMinusWildcard);86// Don't balk at unknown options.87program.unknownOption = NOOP;88/**89 * `$ extens.io`90 */91program.parse(process.argv);92var NO_COMMAND_SPECIFIED = program.args.length === 0;93if (NO_COMMAND_SPECIFIED) {94  program.usageMinusWildcard();...

Full Screen

Full Screen

deb852af4e61d41a1cf2e3e67510646bcc0615c2.svn-base

Source:deb852af4e61d41a1cf2e3e67510646bcc0615c2.svn-base Github

copy

Full Screen

1#!/usr/bin/env node2/**3 * Module dependencies4 */5var _ = require('lodash');6var program = require('./_commander');7var package = require('../package.json');8var NOOP = function() {};9program10  .version(package.version, '-v, --version');11//12// Normalize version argument, i.e.13//14// $ sails -v15// $ sails -V16// $ sails --version17// $ sails version18//19// make `-v` option case-insensitive20process.argv = _.map(process.argv, function(arg) {21  return (arg === '-V') ? '-v' : arg;22});23// $ sails version (--version synonym)24program25  .command('version')26  .description('')27  .action(program.versionInformation);28program29  .option('--silent')30  .option('--verbose')31  .option('--silly')32  .unknownOption = NOOP;33program.usage('[command]');34// $ sails lift35var cmd;36cmd = program.command('lift');37cmd.option('--prod');38cmd.option('--port [port]');39cmd.unknownOption = NOOP;40cmd.description('');41cmd.action(require('./sails-lift'));42// $ sails new <appname>43cmd = program.command('new [path_to_new_app]');44// cmd.option('--dry');45cmd.option('--viewEngine [viewEngine]');46cmd.option('--template [viewEngine]');47cmd.usage('[path_to_new_app]');48cmd.unknownOption = NOOP;49cmd.action(require('./sails-new'));50// $ sails generate <module>51cmd = program.command('generate');52// cmd.option('--dry');53cmd.unknownOption = NOOP;54cmd.description('');55cmd.usage('[something]');56cmd.action(require('./sails-generate'));57// $ sails console58cmd = program.command('console');59cmd.unknownOption = NOOP;60cmd.description('');61cmd.action(require('./sails-console'));62// $ sails www63// Compile `assets` directory into a standalone `www` folder.64cmd = program.command('www');65cmd.unknownOption = NOOP;66cmd.description('');67cmd.action(require('./sails-www'));68// $ sails debug69cmd = program.command('debug');70cmd.unknownOption = NOOP;71cmd.description('');72cmd.action(require('./sails-debug'));73// $ sails configure74cmd = program.command('configure');75cmd.unknownOption = NOOP;76cmd.description('');77cmd.action(require('./sails-configure'));78//79// Normalize help argument, i.e.80//81// $ sails --help82// $ sails help83// $ sails84// $ sails <unrecognized_cmd>85//86// $ sails help (--help synonym)87cmd = program.command('help');88cmd.description('');89cmd.action(program.usageMinusWildcard);90// $ sails <unrecognized_cmd>91// Mask the '*' in `help`.92program93  .command('*')94  .action(program.usageMinusWildcard);95// Don't balk at unknown options96program.unknownOption = NOOP;97// $ sails98//99program.parse(process.argv);100var NO_COMMAND_SPECIFIED = program.args.length === 0;101if (NO_COMMAND_SPECIFIED) {102  program.usageMinusWildcard();...

Full Screen

Full Screen

command.unknownOption.test.js

Source:command.unknownOption.test.js Github

copy

Full Screen

1const commander = require('../');2// Checking for detection of unknown options, including regression tests for some past issues.3describe('unknownOption', () => {4  // Optional. Use internal knowledge to suppress output to keep test output clean.5  let writeErrorSpy;6  beforeAll(() => {7    writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });8  });9  afterEach(() => {10    writeErrorSpy.mockClear();11  });12  afterAll(() => {13    writeErrorSpy.mockRestore();14  });15  test('when specify unknown option with subcommand and action handler then error', () => {16    const program = new commander.Command();17    program18      .exitOverride()19      .command('info')20      .action(() => {});21    let caughtErr;22    try {23      program.parse(['node', 'test', 'info', '--NONSENSE']);24    } catch (err) {25      caughtErr = err;26    }27    expect(caughtErr.code).toBe('commander.unknownOption');28  });29  test('when specify unknown option with subcommand argument and action handler then error', () => {30    const program = new commander.Command();31    program32      .exitOverride()33      .command('info <file>')34      .action(() => {});35    let caughtErr;36    try {37      program.parse(['node', 'test', 'info', 'a', '--NONSENSE']);38    } catch (err) {39      caughtErr = err;40    }41    expect(caughtErr.code).toBe('commander.unknownOption');42  });43  test('when specify unknown option with program and action handler then error', () => {44    const program = new commander.Command();45    program46      .exitOverride()47      .arguments('[file]')48      .action(() => {});49    let caughtErr;50    try {51      program.parse(['node', 'test', '--NONSENSE']);52    } catch (err) {53      caughtErr = err;54    }55    expect(caughtErr.code).toBe('commander.unknownOption');56  });57  test('when specify unknown option with program argument and action handler then error', () => {58    // Regression test from #96559    const program = new commander.Command();60    program61      .exitOverride()62      .arguments('[file]')63      .action(() => {});64    let caughtErr;65    try {66      program.parse(['node', 'test', 'info', 'a', '--NONSENSE']);67    } catch (err) {68      caughtErr = err;69    }70    expect(caughtErr.code).toBe('commander.unknownOption');71  });72  test('when specify unknown option with simple program then error', () => {73    const program = new commander.Command();74    program75      .exitOverride();76    let caughtErr;77    try {78      program.parse(['node', 'test', '--NONSENSE']);79    } catch (err) {80      caughtErr = err;81    }82    expect(caughtErr.code).toBe('commander.unknownOption');83  });...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

1'use strict';2let Arequest,3    request = require('request'),4    _ = require('lodash');5request.debug = false;6Arequest = (defaultOptions) => {7    let arequest;8    Arequest.validateOptions(defaultOptions);9    arequest = async (url, options) => {10        return new Promise((resolve) => {11            Arequest.validateOptions(options);12            options = _.assign({url: url}, options, defaultOptions);13            options = Arequest.mapOptions(options);14            request(options, (error, response) => {15                if (error) {16                    throw new Error(error);17                }18                resolve({19                    statusCode: response.statusCode,20                    headers: response.headers,21                    body: response.body22                });23            });24        });25    };26    arequest.defaults = (options) => {27        if (!options) {28            return defaultOptions;29        }30        if (options.cookieJar === true) {31            options.cookieJar = request.jar();32        }33        return Arequest(options);34    };35    return arequest;36};37/**38 *39 */40Arequest.validateOptions = (options) => {41    let unknownOption;42    if (!options) {43        return;44    }45    unknownOption = _.first(_.difference(_.keys(options), ['method', 'data', 'headers', 'proxy', 'cookieJar', 'cookieJar2']));46    if (unknownOption) {47        throw new Error('Unknown option ("' + unknownOption + '").');48    }49    if (options.method && _.indexOf(['GET', 'POST', 'PUT', 'HEAD', 'DELETE'], options.method) === -1) {50        throw new Error('Unknown option.method value ("' + options.method + '").');51    }52};53/**54 * Map options to meet the request interface.55 */56Arequest.mapOptions = (options) => {57    if (!options) {58        return options;59    }60    if (options.data) {61        options.form = options.data;62        delete options.data;63    }64    if (options.cookieJar) {65        options.jar = options.cookieJar;66        delete options.cookieJar;67    }68    return options;69};...

Full Screen

Full Screen

overwrite.js

Source:overwrite.js Github

copy

Full Screen

...24const optionMissingArgument = overwrite('optionMissingArgument', (option, flag) =>25    o(`缺少选项的必需参数 ${chalk.yellow(option.flags)}${flag ? `,得到了 ${chalk.yellow(flag)}` : ``} .`)26)27module.exports = program => {28    unknownOption(program)29    missingArgument(program)30    optionMissingArgument(program)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.overwrite('visit', (originalFn, url, options) => {2  if (options) {3    return originalFn(url, options);4  }5  return originalFn(url, {6    onBeforeLoad(win) {7      const original = win.console.error;8      cy.stub(win.console, 'error', (msg) => {9        if (msg.includes('Ignoring unknown option')) {10          return null;11        }12        return original.apply(this, arguments);13      }).as('consoleError');14    },15  });16});17Cypress.Commands.overwrite('visit', (originalFn, url, options) => {18  if (options) {19    return originalFn(url, options);20  }21  return originalFn(url, {22    onBeforeLoad(win) {23      const original = win.console.error;24      cy.stub(win.console, 'error', (msg) => {25        if (msg.includes('Ignoring unknown option')) {26          return null;27        }28        return original.apply(this, arguments);29      }).as('consoleError');30    },31  });32});33Cypress.Commands.overwrite('visit', (originalFn, url, options) => {34  if (options) {35    return originalFn(url, options);36  }37  return originalFn(url, {38    onBeforeLoad(win) {39      const original = win.console.error;40      cy.stub(win.console, 'error', (msg) => {41        if (msg.includes('Ignoring unknown option')) {42          return null;43        }44        return original.apply(this, arguments);45      }).as('consoleError');46    },47  });48});49Cypress.Commands.overwrite('visit', (originalFn, url, options) => {50  if (options) {51    return originalFn(url, options);52  }53  return originalFn(url, {54    onBeforeLoad(win) {55      const original = win.console.error;56      cy.stub(win.console, 'error', (msg) => {57        if (msg.includes('Ignoring unknown option')) {58          return null;59        }60        return original.apply(this, arguments);61      }).as('consoleError');62    },63  });64});65Cypress.Commands.overwrite('visit

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.overwrite('log', (originalFn, message, options = {}) => {2  if (options.force) {3    options.consoleProps = () => {4      return {5      }6    }7  }8  return originalFn(message, options)9})10Cypress.Commands.overwrite('log', (originalFn, message, options = {}) => {11  if (options.force) {12    options.consoleProps = () => {13      return {14      }15    }16  }17  return originalFn(message, options)18})19Cypress.Commands.overwrite('log', (originalFn, message, options = {}) => {20  if (options.force) {21    options.consoleProps = () => {22      return {23      }24    }25  }26  return originalFn(message, options)27})28Cypress.Commands.overwrite('log', (originalFn, message, options = {}) => {29  if (options.force) {30    options.consoleProps = () => {31      return {32      }33    }34  }35  return originalFn(message, options)36})37Cypress.Commands.overwrite('log', (originalFn, message, options = {}) => {38  if (options.force) {39    options.consoleProps = () => {40      return {41      }42    }43  }44  return originalFn(message, options)45})46Cypress.Commands.overwrite('log', (originalFn, message, options = {}) => {47  if (options.force) {48    options.consoleProps = () => {49      return {

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.on('uncaught:exception', (err, runnable) => {2})3Cypress.on('uncaught:exception', (err, runnable) => {4})5describe('My First Test', function() {6  it('Does not do much!', function() {7    expect(true).to.equal(true)8  })9})10{11  "env": {12  }13}14describe('My First Test', function() {15  it('Does not do much!', function() {16    expect(true).to.equal(true)17  })18})19describe('My Second Test', function() {20  it('Does not do much!', function() {21    expect(true).to.equal(true)22  })23})24describe('My Third Test', function() {25  it('Does not do much!', function() {26    expect(true).to.equal(true)27  })28})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.overwrite('log', (subject, message, options) => {2  if (options && options.consoleProps) {3    options.consoleProps = () => {4      return {5      }6    }7  }8  return subject(message, options)9})10Cypress.Commands.overwrite('task', (subject, taskName, options) => {11  if (options && options.consoleProps) {12    options.consoleProps = () => {13      return {14      }15    }16  }17  return subject(taskName, options)18})19Cypress.Commands.overwrite('wrap', (subject, obj, options) => {20  if (options && options.consoleProps) {21    options.consoleProps = () => {22      return {23      }24    }25  }26  return subject(obj, options)27})28Cypress.Commands.overwrite('wait', (subject, alias, options) => {29  if (options && options.consoleProps) {30    options.consoleProps = () => {31      return {32      }33    }34  }35  return subject(alias, options)36})37Cypress.Commands.overwrite('writeFile', (subject, filePath, contents, options) => {38  if (options && options.consoleProps) {39    options.consoleProps = () => {40      return {41      }42    }43  }44  return subject(filePath, contents, options)45})46Cypress.Commands.overwrite('wrap', (subject, obj, options) => {47  if (options && options.consoleProps) {48    options.consoleProps = () => {49      return {50      }51    }52  }53  return subject(obj, options)54})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.overwrite('unknownOption', (originalFn, option, args) => {2  if (option === 'config') {3  }4  return originalFn(option, args)5})6import './test'7describe('Test', () => {8  it('should pass', () => {9    cy.get('input').type('hello')10    cy.get('input').type('world')11    cy.get('input').type('{enter}')12    cy.get('body').should('contain', 'Hello world')13  })14})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('unknownOption', (selector, option) => {2    cy.get(selector).click({ force: true }).then((element) => {3        if (element.text() !== option) {4            cy.get('.cdk-overlay-pane').contains(option).click();5        }6    });7});8it('should select an option', () => {9    cy.unknownOption('#mat-select-0', 'Option 2');10});11it('should select an option', () => {12    cy.unknownOption('#mat-select-0', 'Option 2');13});14it('should select an option', () => {15    cy.unknownOption('#mat-select-0', 'Option 2');16});17it('should select an option', () => {18    cy.unknownOption('#mat-select-0', 'Option 2');19});20it('should select an option', () => {21    cy.unknownOption('#mat-select-0', 'Option 2');22});23it('should select an option', () => {24    cy.unknownOption('#mat-select-0', 'Option 2');25});26it('should select an option', () => {27    cy.unknownOption('#mat-select-0', 'Option 2');28});29it('should select an option', () => {30    cy.unknownOption('#mat-select-0', 'Option 2');31});32it('should select an option', () => {33    cy.unknownOption('#mat-select-0', 'Option 2');34});35it('should select an option', () => {36    cy.unknownOption('#mat-select-0', 'Option 2');37});

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.overwrite('log', (log, message, consoleProps) => {2    if (message.includes('Unknown option')) {3    }4    log(message, consoleProps)5})6{7  "env": {8  }9}10{11}12{13  "env": {14  }15}16{17}

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful