How to use clock method in stryker-parent

Best JavaScript code snippet using stryker-parent

picker.time.js

Source:picker.time.js Github

copy

Full Screen

1/*!2 * Time picker for pickadate.js v3.5.63 * http://amsul.github.io/pickadate.js/time.htm4 */5(function ( factory ) {6 // AMD.7 if ( typeof define == 'function' && define.amd )8 define( ['picker', 'jquery'], factory )9 // Node.js/browserify.10 else if ( typeof exports == 'object' )11 module.exports = factory( require('./picker.js'), require('jquery') )12 // Browser globals.13 else factory( Picker, jQuery )14}(function( Picker, $ ) {15/**16 * Globals and constants17 */18var HOURS_IN_DAY = 24,19 MINUTES_IN_HOUR = 60,20 HOURS_TO_NOON = 12,21 MINUTES_IN_DAY = HOURS_IN_DAY * MINUTES_IN_HOUR,22 _ = Picker._23/**24 * The time picker constructor25 */26function TimePicker( picker, settings ) {27 var clock = this,28 elementValue = picker.$node[ 0 ].value,29 elementDataValue = picker.$node.data( 'value' ),30 valueString = elementDataValue || elementValue,31 formatString = elementDataValue ? settings.formatSubmit : settings.format32 clock.settings = settings33 clock.$node = picker.$node34 // The queue of methods that will be used to build item objects.35 clock.queue = {36 interval: 'i',37 min: 'measure create',38 max: 'measure create',39 now: 'now create',40 select: 'parse create validate',41 highlight: 'parse create validate',42 view: 'parse create validate',43 disable: 'deactivate',44 enable: 'activate'45 }46 // The component's item object.47 clock.item = {}48 clock.item.clear = null49 clock.item.interval = settings.interval || 3050 clock.item.disable = ( settings.disable || [] ).slice( 0 )51 clock.item.enable = -(function( collectionDisabled ) {52 return collectionDisabled[ 0 ] === true ? collectionDisabled.shift() : -153 })( clock.item.disable )54 clock.55 set( 'min', settings.min ).56 set( 'max', settings.max ).57 set( 'now' )58 // When there’s a value, set the `select`, which in turn59 // also sets the `highlight` and `view`.60 if ( valueString ) {61 clock.set( 'select', valueString, {62 format: formatString63 })64 }65 // If there’s no value, default to highlighting “today”.66 else {67 clock.68 set( 'select', null ).69 set( 'highlight', clock.item.now )70 }71 // The keycode to movement mapping.72 clock.key = {73 40: 1, // Down74 38: -1, // Up75 39: 1, // Right76 37: -1, // Left77 go: function( timeChange ) {78 clock.set(79 'highlight',80 clock.item.highlight.pick + timeChange * clock.item.interval,81 { interval: timeChange * clock.item.interval }82 )83 this.render()84 }85 }86 // Bind some picker events.87 picker.88 on( 'render', function() {89 var $pickerHolder = picker.$root.children(),90 $viewset = $pickerHolder.find( '.' + settings.klass.viewset ),91 vendors = function( prop ) {92 return ['webkit', 'moz', 'ms', 'o', ''].map(function( vendor ) {93 return ( vendor ? '-' + vendor + '-' : '' ) + prop94 })95 },96 animations = function( $el, state ) {97 vendors( 'transform' ).map(function( prop ) {98 $el.css( prop, state )99 })100 vendors( 'transition' ).map(function( prop ) {101 $el.css( prop, state )102 })103 }104 if ( $viewset.length ) {105 animations( $pickerHolder, 'none' )106 $pickerHolder[ 0 ].scrollTop = ~~$viewset.position().top - ( $viewset[ 0 ].clientHeight * 2 )107 animations( $pickerHolder, '' )108 }109 }, 1 ).110 on( 'open', function() {111 picker.$root.find( 'button' ).attr( 'disabled', false )112 }, 1 ).113 on( 'close', function() {114 picker.$root.find( 'button' ).attr( 'disabled', true )115 }, 1 )116} //TimePicker117/**118 * Set a timepicker item object.119 */120TimePicker.prototype.set = function( type, value, options ) {121 var clock = this,122 clockItem = clock.item123 // If the value is `null` just set it immediately.124 if ( value === null ) {125 if ( type == 'clear' ) type = 'select'126 clockItem[ type ] = value127 return clock128 }129 // Otherwise go through the queue of methods, and invoke the functions.130 // Update this as the time unit, and set the final value as this item.131 // * In the case of `enable`, keep the queue but set `disable` instead.132 // And in the case of `flip`, keep the queue but set `enable` instead.133 clockItem[ ( type == 'enable' ? 'disable' : type == 'flip' ? 'enable' : type ) ] = clock.queue[ type ].split( ' ' ).map( function( method ) {134 value = clock[ method ]( type, value, options )135 return value136 }).pop()137 // Check if we need to cascade through more updates.138 if ( type == 'select' ) {139 clock.set( 'highlight', clockItem.select, options )140 }141 else if ( type == 'highlight' ) {142 clock.set( 'view', clockItem.highlight, options )143 }144 else if ( type == 'interval' ) {145 clock.146 set( 'min', clockItem.min, options ).147 set( 'max', clockItem.max, options )148 }149 else if ( type.match( /^(flip|min|max|disable|enable)$/ ) ) {150 if ( clockItem.select && clock.disabled( clockItem.select ) ) {151 clock.set( 'select', value, options )152 }153 if ( clockItem.highlight && clock.disabled( clockItem.highlight ) ) {154 clock.set( 'highlight', value, options )155 }156 if ( type == 'min' ) {157 clock.set( 'max', clockItem.max, options )158 }159 }160 return clock161} //TimePicker.prototype.set162/**163 * Get a timepicker item object.164 */165TimePicker.prototype.get = function( type ) {166 return this.item[ type ]167} //TimePicker.prototype.get168/**169 * Create a picker time object.170 */171TimePicker.prototype.create = function( type, value, options ) {172 var clock = this173 // If there’s no value, use the type as the value.174 value = value === undefined ? type : value175 // If it’s a date object, convert it into an array.176 if ( _.isDate( value ) ) {177 value = [ value.getHours(), value.getMinutes() ]178 }179 // If it’s an object, use the “pick” value.180 if ( $.isPlainObject( value ) && _.isInteger( value.pick ) ) {181 value = value.pick182 }183 // If it’s an array, convert it into minutes.184 else if ( $.isArray( value ) ) {185 value = +value[ 0 ] * MINUTES_IN_HOUR + (+value[ 1 ])186 }187 // If no valid value is passed, set it to “now”.188 else if ( !_.isInteger( value ) ) {189 value = clock.now( type, value, options )190 }191 // If we’re setting the max, make sure it’s greater than the min.192 if ( type == 'max' && value < clock.item.min.pick ) {193 value += MINUTES_IN_DAY194 }195 // If the value doesn’t fall directly on the interval,196 // add one interval to indicate it as “passed”.197 if ( type != 'min' && type != 'max' && (value - clock.item.min.pick) % clock.item.interval !== 0 ) {198 value += clock.item.interval199 }200 // Normalize it into a “reachable” interval.201 value = clock.normalize( type, value, options )202 // Return the compiled object.203 return {204 // Divide to get hours from minutes.205 hour: ~~( HOURS_IN_DAY + value / MINUTES_IN_HOUR ) % HOURS_IN_DAY,206 // The remainder is the minutes.207 mins: ( MINUTES_IN_HOUR + value % MINUTES_IN_HOUR ) % MINUTES_IN_HOUR,208 // The time in total minutes.209 time: ( MINUTES_IN_DAY + value ) % MINUTES_IN_DAY,210 // Reference to the “relative” value to pick.211 pick: value % MINUTES_IN_DAY212 }213} //TimePicker.prototype.create214/**215 * Create a range limit object using an array, date object,216 * literal “true”, or integer relative to another time.217 */218TimePicker.prototype.createRange = function( from, to ) {219 var clock = this,220 createTime = function( time ) {221 if ( time === true || $.isArray( time ) || _.isDate( time ) ) {222 return clock.create( time )223 }224 return time225 }226 // Create objects if possible.227 if ( !_.isInteger( from ) ) {228 from = createTime( from )229 }230 if ( !_.isInteger( to ) ) {231 to = createTime( to )232 }233 // Create relative times.234 if ( _.isInteger( from ) && $.isPlainObject( to ) ) {235 from = [ to.hour, to.mins + ( from * clock.settings.interval ) ];236 }237 else if ( _.isInteger( to ) && $.isPlainObject( from ) ) {238 to = [ from.hour, from.mins + ( to * clock.settings.interval ) ];239 }240 return {241 from: createTime( from ),242 to: createTime( to )243 }244} //TimePicker.prototype.createRange245/**246 * Check if a time unit falls within a time range object.247 */248TimePicker.prototype.withinRange = function( range, timeUnit ) {249 range = this.createRange(range.from, range.to)250 return timeUnit.pick >= range.from.pick && timeUnit.pick <= range.to.pick251}252/**253 * Check if two time range objects overlap.254 */255TimePicker.prototype.overlapRanges = function( one, two ) {256 var clock = this257 // Convert the ranges into comparable times.258 one = clock.createRange( one.from, one.to )259 two = clock.createRange( two.from, two.to )260 return clock.withinRange( one, two.from ) || clock.withinRange( one, two.to ) ||261 clock.withinRange( two, one.from ) || clock.withinRange( two, one.to )262}263/**264 * Get the time relative to now.265 */266TimePicker.prototype.now = function( type, value/*, options*/ ) {267 var interval = this.item.interval,268 date = new Date(),269 nowMinutes = date.getHours() * MINUTES_IN_HOUR + date.getMinutes(),270 isValueInteger = _.isInteger( value ),271 isBelowInterval272 // Make sure “now” falls within the interval range.273 nowMinutes -= nowMinutes % interval274 // Check if the difference is less than the interval itself.275 isBelowInterval = value < 0 && interval * value + nowMinutes <= -interval276 // Add an interval because the time has “passed”.277 nowMinutes += type == 'min' && isBelowInterval ? 0 : interval278 // If the value is a number, adjust by that many intervals.279 if ( isValueInteger ) {280 nowMinutes += interval * (281 isBelowInterval && type != 'max' ?282 value + 1 :283 value284 )285 }286 // Return the final calculation.287 return nowMinutes288} //TimePicker.prototype.now289/**290 * Normalize minutes to be “reachable” based on the min and interval.291 */292TimePicker.prototype.normalize = function( type, value/*, options*/ ) {293 var interval = this.item.interval,294 minTime = this.item.min && this.item.min.pick || 0295 // If setting min time, don’t shift anything.296 // Otherwise get the value and min difference and then297 // normalize the difference with the interval.298 value -= type == 'min' ? 0 : ( value - minTime ) % interval299 // Return the adjusted value.300 return value301} //TimePicker.prototype.normalize302/**303 * Measure the range of minutes.304 */305TimePicker.prototype.measure = function( type, value, options ) {306 var clock = this307 // If it’s anything false-y, set it to the default.308 if ( !value ) {309 value = type == 'min' ? [ 0, 0 ] : [ HOURS_IN_DAY - 1, MINUTES_IN_HOUR - 1 ]310 }311 // If it’s a string, parse it.312 if ( typeof value == 'string' ) {313 value = clock.parse( type, value )314 }315 // If it’s a literal true, or an integer, make it relative to now.316 else if ( value === true || _.isInteger( value ) ) {317 value = clock.now( type, value, options )318 }319 // If it’s an object already, just normalize it.320 else if ( $.isPlainObject( value ) && _.isInteger( value.pick ) ) {321 value = clock.normalize( type, value.pick, options )322 }323 return value324} ///TimePicker.prototype.measure325/**326 * Validate an object as enabled.327 */328TimePicker.prototype.validate = function( type, timeObject, options ) {329 var clock = this,330 interval = options && options.interval ? options.interval : clock.item.interval331 // Check if the object is disabled.332 if ( clock.disabled( timeObject ) ) {333 // Shift with the interval until we reach an enabled time.334 timeObject = clock.shift( timeObject, interval )335 }336 // Scope the object into range.337 timeObject = clock.scope( timeObject )338 // Do a second check to see if we landed on a disabled min/max.339 // In that case, shift using the opposite interval as before.340 if ( clock.disabled( timeObject ) ) {341 timeObject = clock.shift( timeObject, interval * -1 )342 }343 // Return the final object.344 return timeObject345} //TimePicker.prototype.validate346/**347 * Check if an object is disabled.348 */349TimePicker.prototype.disabled = function( timeToVerify ) {350 var clock = this,351 // Filter through the disabled times to check if this is one.352 isDisabledMatch = clock.item.disable.filter( function( timeToDisable ) {353 // If the time is a number, match the hours.354 if ( _.isInteger( timeToDisable ) ) {355 return timeToVerify.hour == timeToDisable356 }357 // If it’s an array, create the object and match the times.358 if ( $.isArray( timeToDisable ) || _.isDate( timeToDisable ) ) {359 return timeToVerify.pick == clock.create( timeToDisable ).pick360 }361 // If it’s an object, match a time within the “from” and “to” range.362 if ( $.isPlainObject( timeToDisable ) ) {363 return clock.withinRange( timeToDisable, timeToVerify )364 }365 })366 // If this time matches a disabled time, confirm it’s not inverted.367 isDisabledMatch = isDisabledMatch.length && !isDisabledMatch.filter(function( timeToDisable ) {368 return $.isArray( timeToDisable ) && timeToDisable[2] == 'inverted' ||369 $.isPlainObject( timeToDisable ) && timeToDisable.inverted370 }).length371 // If the clock is "enabled" flag is flipped, flip the condition.372 return clock.item.enable === -1 ? !isDisabledMatch : isDisabledMatch ||373 timeToVerify.pick < clock.item.min.pick ||374 timeToVerify.pick > clock.item.max.pick375} //TimePicker.prototype.disabled376/**377 * Shift an object by an interval until we reach an enabled object.378 */379TimePicker.prototype.shift = function( timeObject, interval ) {380 var clock = this,381 minLimit = clock.item.min.pick,382 maxLimit = clock.item.max.pick/*,383 safety = 1000*/384 interval = interval || clock.item.interval385 // Keep looping as long as the time is disabled.386 while ( /*safety &&*/ clock.disabled( timeObject ) ) {387 /*safety -= 1388 if ( !safety ) {389 throw 'Fell into an infinite loop while shifting to ' + timeObject.hour + ':' + timeObject.mins + '.'390 }*/391 // Increase/decrease the time by the interval and keep looping.392 timeObject = clock.create( timeObject.pick += interval )393 // If we've looped beyond the limits, break out of the loop.394 if ( timeObject.pick <= minLimit || timeObject.pick >= maxLimit ) {395 break396 }397 }398 // Return the final object.399 return timeObject400} //TimePicker.prototype.shift401/**402 * Scope an object to be within range of min and max.403 */404TimePicker.prototype.scope = function( timeObject ) {405 var minLimit = this.item.min.pick,406 maxLimit = this.item.max.pick407 return this.create( timeObject.pick > maxLimit ? maxLimit : timeObject.pick < minLimit ? minLimit : timeObject )408} //TimePicker.prototype.scope409/**410 * Parse a string into a usable type.411 */412TimePicker.prototype.parse = function( type, value, options ) {413 var hour, minutes, isPM, item, parseValue,414 clock = this,415 parsingObject = {}416 // If it’s already parsed, we’re good.417 if ( !value || typeof value != 'string' ) {418 return value419 }420 // We need a `.format` to parse the value with.421 if ( !( options && options.format ) ) {422 options = options || {}423 options.format = clock.settings.format424 }425 // Convert the format into an array and then map through it.426 clock.formats.toArray( options.format ).map( function( label ) {427 var428 substring,429 // Grab the formatting label.430 formattingLabel = clock.formats[ label ],431 // The format length is from the formatting label function or the432 // label length without the escaping exclamation (!) mark.433 formatLength = formattingLabel ?434 _.trigger( formattingLabel, clock, [ value, parsingObject ] ) :435 label.replace( /^!/, '' ).length436 // If there's a format label, split the value up to the format length.437 // Then add it to the parsing object with appropriate label.438 if ( formattingLabel ) {439 substring = value.substr( 0, formatLength )440 parsingObject[ label ] = substring.match(/^\d+$/) ? +substring : substring441 }442 // Update the time value as the substring from format length to end.443 value = value.substr( formatLength )444 })445 // Grab the hour and minutes from the parsing object.446 for ( item in parsingObject ) {447 parseValue = parsingObject[item]448 if ( _.isInteger(parseValue) ) {449 if ( item.match(/^(h|hh)$/i) ) {450 hour = parseValue451 if ( item == 'h' || item == 'hh' ) {452 hour %= 12453 }454 }455 else if ( item == 'i' ) {456 minutes = parseValue457 }458 }459 else if ( item.match(/^a$/i) && parseValue.match(/^p/i) && ('h' in parsingObject || 'hh' in parsingObject) ) {460 isPM = true461 }462 }463 // Calculate it in minutes and return.464 return (isPM ? hour + 12 : hour) * MINUTES_IN_HOUR + minutes465} //TimePicker.prototype.parse466/**467 * Various formats to display the object in.468 */469TimePicker.prototype.formats = {470 h: function( string, timeObject ) {471 // If there's string, then get the digits length.472 // Otherwise return the selected hour in "standard" format.473 return string ? _.digits( string ) : timeObject.hour % HOURS_TO_NOON || HOURS_TO_NOON474 },475 hh: function( string, timeObject ) {476 // If there's a string, then the length is always 2.477 // Otherwise return the selected hour in "standard" format with a leading zero.478 return string ? 2 : _.lead( timeObject.hour % HOURS_TO_NOON || HOURS_TO_NOON )479 },480 H: function( string, timeObject ) {481 // If there's string, then get the digits length.482 // Otherwise return the selected hour in "military" format as a string.483 return string ? _.digits( string ) : '' + ( timeObject.hour % 24 )484 },485 HH: function( string, timeObject ) {486 // If there's string, then get the digits length.487 // Otherwise return the selected hour in "military" format with a leading zero.488 return string ? _.digits( string ) : _.lead( timeObject.hour % 24 )489 },490 i: function( string, timeObject ) {491 // If there's a string, then the length is always 2.492 // Otherwise return the selected minutes.493 return string ? 2 : _.lead( timeObject.mins )494 },495 a: function( string, timeObject ) {496 // If there's a string, then the length is always 4.497 // Otherwise check if it's more than "noon" and return either am/pm.498 return string ? 4 : MINUTES_IN_DAY / 2 > timeObject.time % MINUTES_IN_DAY ? 'a.m.' : 'p.m.'499 },500 A: function( string, timeObject ) {501 // If there's a string, then the length is always 2.502 // Otherwise check if it's more than "noon" and return either am/pm.503 return string ? 2 : MINUTES_IN_DAY / 2 > timeObject.time % MINUTES_IN_DAY ? 'AM' : 'PM'504 },505 // Create an array by splitting the formatting string passed.506 toArray: function( formatString ) { return formatString.split( /(h{1,2}|H{1,2}|i|a|A|!.)/g ) },507 // Format an object into a string using the formatting options.508 toString: function ( formatString, itemObject ) {509 var clock = this510 return clock.formats.toArray( formatString ).map( function( label ) {511 return _.trigger( clock.formats[ label ], clock, [ 0, itemObject ] ) || label.replace( /^!/, '' )512 }).join( '' )513 }514} //TimePicker.prototype.formats515/**516 * Check if two time units are the exact.517 */518TimePicker.prototype.isTimeExact = function( one, two ) {519 var clock = this520 // When we’re working with minutes, do a direct comparison.521 if (522 ( _.isInteger( one ) && _.isInteger( two ) ) ||523 ( typeof one == 'boolean' && typeof two == 'boolean' )524 ) {525 return one === two526 }527 // When we’re working with time representations, compare the “pick” value.528 if (529 ( _.isDate( one ) || $.isArray( one ) ) &&530 ( _.isDate( two ) || $.isArray( two ) )531 ) {532 return clock.create( one ).pick === clock.create( two ).pick533 }534 // When we’re working with range objects, compare the “from” and “to”.535 if ( $.isPlainObject( one ) && $.isPlainObject( two ) ) {536 return clock.isTimeExact( one.from, two.from ) && clock.isTimeExact( one.to, two.to )537 }538 return false539}540/**541 * Check if two time units overlap.542 */543TimePicker.prototype.isTimeOverlap = function( one, two ) {544 var clock = this545 // When we’re working with an integer, compare the hours.546 if ( _.isInteger( one ) && ( _.isDate( two ) || $.isArray( two ) ) ) {547 return one === clock.create( two ).hour548 }549 if ( _.isInteger( two ) && ( _.isDate( one ) || $.isArray( one ) ) ) {550 return two === clock.create( one ).hour551 }552 // When we’re working with range objects, check if the ranges overlap.553 if ( $.isPlainObject( one ) && $.isPlainObject( two ) ) {554 return clock.overlapRanges( one, two )555 }556 return false557}558/**559 * Flip the “enabled” state.560 */561TimePicker.prototype.flipEnable = function(val) {562 var itemObject = this.item563 itemObject.enable = val || (itemObject.enable == -1 ? 1 : -1)564}565/**566 * Mark a collection of times as “disabled”.567 */568TimePicker.prototype.deactivate = function( type, timesToDisable ) {569 var clock = this,570 disabledItems = clock.item.disable.slice(0)571 // If we’re flipping, that’s all we need to do.572 if ( timesToDisable == 'flip' ) {573 clock.flipEnable()574 }575 else if ( timesToDisable === false ) {576 clock.flipEnable(1)577 disabledItems = []578 }579 else if ( timesToDisable === true ) {580 clock.flipEnable(-1)581 disabledItems = []582 }583 // Otherwise go through the times to disable.584 else {585 timesToDisable.map(function( unitToDisable ) {586 var matchFound587 // When we have disabled items, check for matches.588 // If something is matched, immediately break out.589 for ( var index = 0; index < disabledItems.length; index += 1 ) {590 if ( clock.isTimeExact( unitToDisable, disabledItems[index] ) ) {591 matchFound = true592 break593 }594 }595 // If nothing was found, add the validated unit to the collection.596 if ( !matchFound ) {597 if (598 _.isInteger( unitToDisable ) ||599 _.isDate( unitToDisable ) ||600 $.isArray( unitToDisable ) ||601 ( $.isPlainObject( unitToDisable ) && unitToDisable.from && unitToDisable.to )602 ) {603 disabledItems.push( unitToDisable )604 }605 }606 })607 }608 // Return the updated collection.609 return disabledItems610} //TimePicker.prototype.deactivate611/**612 * Mark a collection of times as “enabled”.613 */614TimePicker.prototype.activate = function( type, timesToEnable ) {615 var clock = this,616 disabledItems = clock.item.disable,617 disabledItemsCount = disabledItems.length618 // If we’re flipping, that’s all we need to do.619 if ( timesToEnable == 'flip' ) {620 clock.flipEnable()621 }622 else if ( timesToEnable === true ) {623 clock.flipEnable(1)624 disabledItems = []625 }626 else if ( timesToEnable === false ) {627 clock.flipEnable(-1)628 disabledItems = []629 }630 // Otherwise go through the disabled times.631 else {632 timesToEnable.map(function( unitToEnable ) {633 var matchFound,634 disabledUnit,635 index,636 isRangeMatched637 // Go through the disabled items and try to find a match.638 for ( index = 0; index < disabledItemsCount; index += 1 ) {639 disabledUnit = disabledItems[index]640 // When an exact match is found, remove it from the collection.641 if ( clock.isTimeExact( disabledUnit, unitToEnable ) ) {642 matchFound = disabledItems[index] = null643 isRangeMatched = true644 break645 }646 // When an overlapped match is found, add the “inverted” state to it.647 else if ( clock.isTimeOverlap( disabledUnit, unitToEnable ) ) {648 if ( $.isPlainObject( unitToEnable ) ) {649 unitToEnable.inverted = true650 matchFound = unitToEnable651 }652 else if ( $.isArray( unitToEnable ) ) {653 matchFound = unitToEnable654 if ( !matchFound[2] ) matchFound.push( 'inverted' )655 }656 else if ( _.isDate( unitToEnable ) ) {657 matchFound = [ unitToEnable.getFullYear(), unitToEnable.getMonth(), unitToEnable.getDate(), 'inverted' ]658 }659 break660 }661 }662 // If a match was found, remove a previous duplicate entry.663 if ( matchFound ) for ( index = 0; index < disabledItemsCount; index += 1 ) {664 if ( clock.isTimeExact( disabledItems[index], unitToEnable ) ) {665 disabledItems[index] = null666 break667 }668 }669 // In the event that we’re dealing with an overlap of range times,670 // make sure there are no “inverted” times because of it.671 if ( isRangeMatched ) for ( index = 0; index < disabledItemsCount; index += 1 ) {672 if ( clock.isTimeOverlap( disabledItems[index], unitToEnable ) ) {673 disabledItems[index] = null674 break675 }676 }677 // If something is still matched, add it into the collection.678 if ( matchFound ) {679 disabledItems.push( matchFound )680 }681 })682 }683 // Return the updated collection.684 return disabledItems.filter(function( val ) { return val != null })685} //TimePicker.prototype.activate686/**687 * The division to use for the range intervals.688 */689TimePicker.prototype.i = function( type, value/*, options*/ ) {690 return _.isInteger( value ) && value > 0 ? value : this.item.interval691}692/**693 * Create a string for the nodes in the picker.694 */695TimePicker.prototype.nodes = function( isOpen ) {696 var697 clock = this,698 settings = clock.settings,699 selectedObject = clock.item.select,700 highlightedObject = clock.item.highlight,701 viewsetObject = clock.item.view,702 disabledCollection = clock.item.disable703 return _.node(704 'ul',705 _.group({706 min: clock.item.min.pick,707 max: clock.item.max.pick,708 i: clock.item.interval,709 node: 'li',710 item: function( loopedTime ) {711 loopedTime = clock.create( loopedTime )712 var timeMinutes = loopedTime.pick,713 isSelected = selectedObject && selectedObject.pick == timeMinutes,714 isHighlighted = highlightedObject && highlightedObject.pick == timeMinutes,715 isDisabled = disabledCollection && clock.disabled( loopedTime ),716 formattedTime = _.trigger( clock.formats.toString, clock, [ settings.format, loopedTime ] )717 return [718 _.trigger( clock.formats.toString, clock, [ _.trigger( settings.formatLabel, clock, [ loopedTime ] ) || settings.format, loopedTime ] ),719 (function( klasses ) {720 if ( isSelected ) {721 klasses.push( settings.klass.selected )722 }723 if ( isHighlighted ) {724 klasses.push( settings.klass.highlighted )725 }726 if ( viewsetObject && viewsetObject.pick == timeMinutes ) {727 klasses.push( settings.klass.viewset )728 }729 if ( isDisabled ) {730 klasses.push( settings.klass.disabled )731 }732 return klasses.join( ' ' )733 })( [ settings.klass.listItem ] ),734 'data-pick=' + loopedTime.pick + ' ' + _.ariaAttr({735 role: 'option',736 label: formattedTime,737 selected: isSelected && clock.$node.val() === formattedTime ? true : null,738 activedescendant: isHighlighted ? true : null,739 disabled: isDisabled ? true : null740 })741 ]742 }743 }) +744 // * For Firefox forms to submit, make sure to set the button’s `type` attribute as “button”.745 _.node(746 'li',747 _.node(748 'button',749 settings.clear,750 settings.klass.buttonClear,751 'type=button data-clear=1' + ( isOpen ? '' : ' disabled' ) + ' ' +752 _.ariaAttr({ controls: clock.$node[0].id })753 ),754 '', _.ariaAttr({ role: 'presentation' })755 ),756 settings.klass.list,757 _.ariaAttr({ role: 'listbox', controls: clock.$node[0].id })758 )759} //TimePicker.prototype.nodes760/**761 * Extend the picker to add the component with the defaults.762 */763TimePicker.defaults = (function( prefix ) {764 return {765 // Clear766 clear: 'Clear',767 // The format to show on the `input` element768 format: 'h:i A',769 // The interval between each time770 interval: 30,771 // Picker close behavior772 closeOnSelect: true,773 closeOnClear: true,774 // Classes775 klass: {776 picker: prefix + ' ' + prefix + '--time',777 holder: prefix + '__holder',778 list: prefix + '__list',779 listItem: prefix + '__list-item',780 disabled: prefix + '__list-item--disabled',781 selected: prefix + '__list-item--selected',782 highlighted: prefix + '__list-item--highlighted',783 viewset: prefix + '__list-item--viewset',784 now: prefix + '__list-item--now',785 buttonClear: prefix + '__button--clear'786 }787 }788})( Picker.klasses().picker )789/**790 * Extend the picker to add the time picker.791 */792Picker.extend( 'pickatime', TimePicker )...

Full Screen

Full Screen

mockclock_test.js

Source:mockclock_test.js Github

copy

Full Screen

1// Copyright 2007 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14goog.provide('goog.testing.MockClockTest');15goog.setTestOnly('goog.testing.MockClockTest');16goog.require('goog.Promise');17goog.require('goog.Timer');18goog.require('goog.events');19goog.require('goog.functions');20goog.require('goog.testing.MockClock');21goog.require('goog.testing.PropertyReplacer');22goog.require('goog.testing.jsunit');23goog.require('goog.testing.recordFunction');24var stubs = new goog.testing.PropertyReplacer();25function tearDown() {26 stubs.reset();27}28function testMockClockWasInstalled() {29 var clock = new goog.testing.MockClock();30 var originalTimeout = window.setTimeout;31 clock.install();32 assertNotEquals(window.setTimeout, originalTimeout);33 setTimeout(function() {}, 100);34 assertEquals(1, clock.getTimeoutsMade());35 setInterval(function() {}, 200);36 assertEquals(2, clock.getTimeoutsMade());37 clock.uninstall();38 assertEquals(window.setTimeout, originalTimeout);39 assertNull(clock.replacer_);40}41function testSetTimeoutAndTick() {42 var clock = new goog.testing.MockClock(true);43 var m5 = false, m10 = false, m15 = false, m20 = false;44 setTimeout(function() { m5 = true; }, 5);45 setTimeout(function() { m10 = true; }, 10);46 setTimeout(function() { m15 = true; }, 15);47 setTimeout(function() { m20 = true; }, 20);48 assertEquals(4, clock.getTimeoutsMade());49 assertEquals(4, clock.tick(4));50 assertEquals(4, clock.getCurrentTime());51 assertFalse(m5);52 assertFalse(m10);53 assertFalse(m15);54 assertFalse(m20);55 assertEquals(5, clock.tick(1));56 assertEquals(5, clock.getCurrentTime());57 assertTrue('m5 should now be true', m5);58 assertFalse(m10);59 assertFalse(m15);60 assertFalse(m20);61 assertEquals(10, clock.tick(5));62 assertEquals(10, clock.getCurrentTime());63 assertTrue('m5 should be true', m5);64 assertTrue('m10 should now be true', m10);65 assertFalse(m15);66 assertFalse(m20);67 assertEquals(15, clock.tick(5));68 assertEquals(15, clock.getCurrentTime());69 assertTrue('m5 should be true', m5);70 assertTrue('m10 should be true', m10);71 assertTrue('m15 should now be true', m15);72 assertFalse(m20);73 assertEquals(20, clock.tick(5));74 assertEquals(20, clock.getCurrentTime());75 assertTrue('m5 should be true', m5);76 assertTrue('m10 should be true', m10);77 assertTrue('m15 should be true', m15);78 assertTrue('m20 should now be true', m20);79 clock.uninstall();80}81function testSetImmediateAndTick() {82 var clock = new goog.testing.MockClock(true);83 var tick0 = false;84 var tick1 = false;85 setImmediate(function() { tick0 = true; });86 setImmediate(function() { tick1 = true; });87 assertEquals(2, clock.getTimeoutsMade());88 clock.tick(0);89 assertTrue(tick0);90 assertTrue(tick1);91 clock.uninstall();92}93function testSetInterval() {94 var clock = new goog.testing.MockClock(true);95 var times = 0;96 setInterval(function() { times++; }, 100);97 clock.tick(500);98 assertEquals(5, times);99 clock.tick(100);100 assertEquals(6, times);101 clock.tick(100);102 assertEquals(7, times);103 clock.tick(50);104 assertEquals(7, times);105 clock.tick(50);106 assertEquals(8, times);107 clock.uninstall();108}109function testRequestAnimationFrame() {110 goog.global.requestAnimationFrame = function() {111 };112 var clock = new goog.testing.MockClock(true);113 var times = [];114 var recFunc = goog.testing.recordFunction(function(now) {115 times.push(now);116 });117 goog.global.requestAnimationFrame(recFunc);118 clock.tick(50);119 assertEquals(1, recFunc.getCallCount());120 assertEquals(20, times[0]);121 goog.global.requestAnimationFrame(recFunc);122 clock.tick(100);123 assertEquals(2, recFunc.getCallCount());124 assertEquals(70, times[1]);125 clock.uninstall();126}127function testClearTimeout() {128 var clock = new goog.testing.MockClock(true);129 var ran = false;130 var c = setTimeout(function() { ran = true; }, 100);131 clock.tick(50);132 assertFalse(ran);133 clearTimeout(c);134 clock.tick(100);135 assertFalse(ran);136 clock.uninstall();137}138function testClearInterval() {139 var clock = new goog.testing.MockClock(true);140 var times = 0;141 var c = setInterval(function() { times++; }, 100);142 clock.tick(500);143 assertEquals(5, times);144 clock.tick(100);145 assertEquals(6, times);146 clock.tick(100);147 clearInterval(c);148 assertEquals(7, times);149 clock.tick(50);150 assertEquals(7, times);151 clock.tick(50);152 assertEquals(7, times);153 clock.uninstall();154}155function testClearInterval2() {156 // Tests that we can clear the interval from inside the function157 var clock = new goog.testing.MockClock(true);158 var times = 0;159 var c = setInterval(function() {160 times++;161 if (times == 6) {162 clearInterval(c);163 }164 }, 100);165 clock.tick(500);166 assertEquals(5, times);167 clock.tick(100);168 assertEquals(6, times);169 clock.tick(100);170 assertEquals(6, times);171 clock.tick(50);172 assertEquals(6, times);173 clock.tick(50);174 assertEquals(6, times);175 clock.uninstall();176}177function testCancelRequestAnimationFrame() {178 goog.global.requestAnimationFrame = function() {179 };180 goog.global.cancelRequestAnimationFrame = function() {181 };182 var clock = new goog.testing.MockClock(true);183 var ran = false;184 var c = goog.global.requestAnimationFrame(function() { ran = true; });185 clock.tick(10);186 assertFalse(ran);187 goog.global.cancelRequestAnimationFrame(c);188 clock.tick(20);189 assertFalse(ran);190 clock.uninstall();191}192function testMockGoogNow() {193 assertNotEquals(0, goog.now());194 var clock = new goog.testing.MockClock(true);195 assertEquals(0, goog.now());196 clock.tick(50);197 assertEquals(50, goog.now());198 clock.uninstall();199 assertNotEquals(50, goog.now());200}201function testTimeoutDelay() {202 var clock = new goog.testing.MockClock(true);203 var m5 = false, m10 = false, m20 = false;204 setTimeout(function() { m5 = true; }, 5);205 setTimeout(function() { m10 = true; }, 10);206 setTimeout(function() { m20 = true; }, 20);207 // Fire 3ms early, so m5 fires at t=2208 clock.setTimeoutDelay(-3);209 clock.tick(1);210 assertFalse(m5);211 assertFalse(m10);212 clock.tick(1);213 assertTrue(m5);214 assertFalse(m10);215 // Fire 3ms late, so m10 fires at t=13216 clock.setTimeoutDelay(3);217 assertEquals(12, clock.tick(10));218 assertEquals(12, clock.getCurrentTime());219 assertFalse(m10);220 clock.tick(1);221 assertTrue(m10);222 assertFalse(m20);223 // Fire 10ms early, so m20 fires now, since it's after t=10224 clock.setTimeoutDelay(-10);225 assertFalse(m20);226 assertEquals(14, clock.tick(1));227 assertEquals(14, clock.getCurrentTime());228 assertTrue(m20);229 clock.uninstall();230}231function testTimerCallbackCanCreateIntermediateTimer() {232 var clock = new goog.testing.MockClock(true);233 var sequence = [];234 // Create 3 timers: 1, 2, and 3. Timer 1 should fire at T=1, timer 2 at235 // T=2, and timer 3 at T=3. The catch: Timer 2 is created by the236 // callback within timer 0.237 // Testing method: Create a simple string sequencing each timer and at238 // what time it fired.239 setTimeout(function() {240 sequence.push('timer1 at T=' + goog.now());241 setTimeout(function() {242 sequence.push('timer2 at T=' + goog.now());243 }, 1);244 }, 1);245 setTimeout(function() {246 sequence.push('timer3 at T=' + goog.now());247 }, 3);248 clock.tick(4);249 assertEquals(250 'Each timer should fire in sequence at the correct time.',251 'timer1 at T=1, timer2 at T=2, timer3 at T=3',252 sequence.join(', '));253 clock.uninstall();254}255function testCorrectArgumentsPassedToCallback() {256 var clock = new goog.testing.MockClock(true);257 var timeoutId;258 var timeoutExecuted = false;259 timeoutId = setTimeout(function(arg) {260 assertEquals('"this" must be goog.global',261 goog.global, this);262 assertEquals('The timeout ID must be the first parameter',263 timeoutId, arg);264 assertEquals('Exactly one argument must be passed',265 1, arguments.length);266 timeoutExecuted = true;267 }, 1);268 clock.tick(4);269 assertTrue('The timeout was not executed', timeoutExecuted);270 clock.uninstall();271}272function testTickZero() {273 var clock = new goog.testing.MockClock(true);274 var calls = 0;275 setTimeout(function() {276 assertEquals('I need to be first', 0, calls);277 calls++;278 }, 0);279 setTimeout(function() {280 assertEquals('I need to be second', 1, calls);281 calls++;282 }, 0);283 clock.tick(0);284 assertEquals(2, calls);285 setTimeout(function() {286 assertEquals('I need to be third', 2, calls);287 calls++;288 }, 0);289 clock.tick(0);290 assertEquals(3, calls);291 assertEquals('Time should still be zero', 0, goog.now());292 clock.uninstall();293}294function testReset() {295 var clock = new goog.testing.MockClock(true);296 var id = setTimeout(function() {297 fail('Timeouts should be cleared after a reset');298 }, 0);299 clock.reset();300 clock.tick(999999);301 var calls = 0;302 setTimeout(function() { calls++; }, 10);303 clearTimeout(id);304 clock.tick(100);305 assertEquals('New timeout should still run after clearing from before reset',306 1, calls);307 clock.uninstall();308}309function testNewClockWithOldTimeoutId() {310 var clock = new goog.testing.MockClock(true);311 var id = setTimeout(function() {312 fail('Timeouts should be cleared after uninstall');313 }, 0);314 clock.uninstall();315 clock = new goog.testing.MockClock(true);316 var calls = 0;317 setTimeout(function() { calls++; }, 10);318 clearTimeout(id);319 clock.tick(100);320 assertEquals('Timeout should still run after cancelling from old clock',321 1, calls);322 clock.uninstall();323}324function testQueueInsertionHelper() {325 var queue = [];326 function queueToString() {327 var buffer = [];328 for (var i = 0; i < queue.length; i++) {329 buffer.push(queue[i].runAtMillis);330 }331 return buffer.join(',');332 }333 goog.testing.MockClock.insert_({runAtMillis: 2}, queue);334 assertEquals('Only item',335 '2', queueToString());336 goog.testing.MockClock.insert_({runAtMillis: 4}, queue);337 assertEquals('Biggest item',338 '4,2', queueToString());339 goog.testing.MockClock.insert_({runAtMillis: 5}, queue);340 assertEquals('An even bigger item',341 '5,4,2', queueToString());342 goog.testing.MockClock.insert_({runAtMillis: 1}, queue);343 assertEquals('Smallest item',344 '5,4,2,1', queueToString());345 goog.testing.MockClock.insert_({runAtMillis: 1, dup: true}, queue);346 assertEquals('Duplicate smallest item',347 '5,4,2,1,1', queueToString());348 assertTrue('Duplicate item comes at a smaller index', queue[3].dup);349 goog.testing.MockClock.insert_({runAtMillis: 3}, queue);350 goog.testing.MockClock.insert_({runAtMillis: 3, dup: true}, queue);351 assertEquals('Duplicate a middle item',352 '5,4,3,3,2,1,1', queueToString());353 assertTrue('Duplicate item comes at a smaller index', queue[2].dup);354}355function testIsTimeoutSet() {356 var clock = new goog.testing.MockClock(true);357 var timeoutKey = setTimeout(function() {}, 1);358 assertTrue('Timeout ' + timeoutKey + ' should be set',359 clock.isTimeoutSet(timeoutKey));360 var nextTimeoutKey = timeoutKey + 1;361 assertFalse('Timeout ' + nextTimeoutKey + ' should not be set',362 clock.isTimeoutSet(nextTimeoutKey));363 clearTimeout(timeoutKey);364 assertFalse('Timeout ' + timeoutKey + ' should no longer be set',365 clock.isTimeoutSet(timeoutKey));366 var newTimeoutKey = setTimeout(function() {}, 1);367 clock.tick(5);368 assertFalse('Timeout ' + timeoutKey + ' should not be set',369 clock.isTimeoutSet(timeoutKey));370 assertTrue('Timeout ' + newTimeoutKey + ' should be set',371 clock.isTimeoutSet(newTimeoutKey));372 clock.uninstall();373}374function testBalksOnTimeoutsGreaterThanMaxInt() {375 // Browsers have trouble with timeout greater than max int, so we376 // want Mock Clock to fail if this happens.377 var clock = new goog.testing.MockClock(true);378 // Functions on window don't seem to be able to throw exceptions in379 // IE6. Explicitly reading the property makes it work.380 var setTimeout = window.setTimeout;381 assertThrows('Timeouts > MAX_INT should fail',382 function() {383 setTimeout(goog.nullFunction, 2147483648);384 });385 assertThrows('Timeouts much greater than MAX_INT should fail',386 function() {387 setTimeout(goog.nullFunction, 2147483648 * 10);388 });389 clock.uninstall();390}391function testCorrectSetTimeoutIsRestored() {392 var safe = goog.functions.error('should not have been called');393 stubs.set(window, 'setTimeout', safe);394 var clock = new goog.testing.MockClock(true);395 assertNotEquals('setTimeout is replaced', safe, window.setTimeout);396 clock.uninstall();397 // NOTE: If this assertion proves to be flaky in IE, the string value of398 // the two functions have to be compared as described in399 // goog.testing.TestCase#finalize.400 assertEquals('setTimeout is restored', safe, window.setTimeout);401}402function testMozRequestAnimationFrame() {403 // Setting this function will indirectly tell the mock clock to mock it out.404 stubs.set(window, 'mozRequestAnimationFrame', goog.nullFunction);405 var clock = new goog.testing.MockClock(true);406 var mozBeforePaint = goog.testing.recordFunction();407 goog.events.listen(window, 'MozBeforePaint', mozBeforePaint);408 window.mozRequestAnimationFrame(null);409 assertEquals(0, mozBeforePaint.getCallCount());410 clock.tick(goog.testing.MockClock.REQUEST_ANIMATION_FRAME_TIMEOUT);411 assertEquals(1, mozBeforePaint.getCallCount());412 clock.dispose();413}414function testClearBeforeSet() {415 var clock = new goog.testing.MockClock(true);416 var expectedId = goog.testing.MockClock.nextId;417 window.clearTimeout(expectedId);418 var fn = goog.testing.recordFunction();419 var actualId = window.setTimeout(fn, 0);420 assertEquals(421 'In order for this test to work, we have to guess the ids in advance',422 expectedId, actualId);423 clock.tick(1);424 assertEquals(1, fn.getCallCount());425 clock.dispose();426}427function testNonFunctionArguments() {428 var clock = new goog.testing.MockClock(true);429 // Unlike normal setTimeout and friends, we only accept functions (not430 // strings, not undefined, etc). Make sure that if we get a non-function, we431 // fail early rather than on the next .tick() operation.432 assertThrows('setTimeout with a non-function value should fail',433 function() {434 window.setTimeout(undefined, 0);435 });436 clock.tick(1);437 assertThrows('setTimeout with a string should fail',438 function() {439 window.setTimeout('throw new Error("setTimeout string eval!");', 0);440 });441 clock.tick(1);442 clock.dispose();443}444function testUnspecifiedTimeout() {445 var clock = new goog.testing.MockClock(true);446 var m0a = false, m0b = false, m10 = false;447 setTimeout(function() { m0a = true; });448 setTimeout(function() { m10 = true; }, 10);449 assertEquals(2, clock.getTimeoutsMade());450 assertFalse(m0a);451 assertFalse(m0b);452 assertFalse(m10);453 assertEquals(0, clock.tick(0));454 assertEquals(0, clock.getCurrentTime());455 assertTrue(m0a);456 assertFalse(m0b);457 assertFalse(m10);458 setTimeout(function() { m0b = true; });459 assertEquals(3, clock.getTimeoutsMade());460 assertEquals(0, clock.tick(0));461 assertEquals(0, clock.getCurrentTime());462 assertTrue(m0a);463 assertTrue(m0b);464 assertFalse(m10);465 assertEquals(10, clock.tick(10));466 assertEquals(10, clock.getCurrentTime());467 assertTrue(m0a);468 assertTrue(m0b);469 assertTrue(m10);470 clock.uninstall();471}472function testUnspecifiedInterval() {473 var clock = new goog.testing.MockClock(true);474 var times = 0;475 var handle = setInterval(function() {476 if (++times >= 5) {477 clearInterval(handle);478 }479 });480 clock.tick(0);481 assertEquals(5, times);482 clock.uninstall();483}484function testTickPromise() {485 var clock = new goog.testing.MockClock(true);486 var p = goog.Promise.resolve('foo');487 assertEquals('foo', clock.tickPromise(p));488 var rejected = goog.Promise.reject(new Error('failed'));489 var e = assertThrows(function() {490 clock.tickPromise(rejected);491 });492 assertEquals('failed', e.message);493 var delayed = goog.Timer.promise(500, 'delayed');494 e = assertThrows(function() {495 clock.tickPromise(delayed);496 });497 assertEquals('Promise was expected to be resolved after mock clock tick.',498 e.message);499 assertEquals('delayed', clock.tickPromise(delayed, 500));500 clock.dispose();...

Full Screen

Full Screen

DateTimeShortcuts.js

Source:DateTimeShortcuts.js Github

copy

Full Screen

1// Inserts shortcut buttons after all of the following:2// <input type="text" class="vDateField">3// <input type="text" class="vTimeField">4var DateTimeShortcuts = {5 calendars: [],6 calendarInputs: [],7 clockInputs: [],8 dismissClockFunc: [],9 dismissCalendarFunc: [],10 calendarDivName1: 'calendarbox', // name of calendar <div> that gets toggled11 calendarDivName2: 'calendarin', // name of <div> that contains calendar12 calendarLinkName: 'calendarlink',// name of the link that is used to toggle13 clockDivName: 'clockbox', // name of clock <div> that gets toggled14 clockLinkName: 'clocklink', // name of the link that is used to toggle15 shortCutsClass: 'datetimeshortcuts', // class of the clock and cal shortcuts16 admin_media_prefix: '',17 init: function() {18 // Get admin_media_prefix by grabbing it off the window object. It's19 // set in the admin/base.html template, so if it's not there, someone's20 // overridden the template. In that case, we'll set a clearly-invalid21 // value in the hopes that someone will examine HTTP requests and see it.22 if (window.__admin_media_prefix__ != undefined) {23 DateTimeShortcuts.admin_media_prefix = window.__admin_media_prefix__;24 } else {25 DateTimeShortcuts.admin_media_prefix = '/missing-admin-media-prefix/';26 }27 var inputs = document.getElementsByTagName('input');28 for (i=0; i<inputs.length; i++) {29 var inp = inputs[i];30 if (inp.getAttribute('type') == 'text' && inp.className.match(/vTimeField/)) {31 DateTimeShortcuts.addClock(inp);32 }33 else if (inp.getAttribute('type') == 'text' && inp.className.match(/vDateField/)) {34 DateTimeShortcuts.addCalendar(inp);35 }36 }37 },38 // Add clock widget to a given field39 addClock: function(inp) {40 var num = DateTimeShortcuts.clockInputs.length;41 DateTimeShortcuts.clockInputs[num] = inp;42 DateTimeShortcuts.dismissClockFunc[num] = function() { DateTimeShortcuts.dismissClock(num); return true; };43 // Shortcut links (clock icon and "Now" link)44 var shortcuts_span = document.createElement('span');45 shortcuts_span.className = DateTimeShortcuts.shortCutsClass;46 inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling);47 var now_link = document.createElement('a');48 now_link.setAttribute('href', "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().strftime('" + get_format('TIME_INPUT_FORMATS')[0] + "'));");49 now_link.appendChild(document.createTextNode(gettext('Now')));50 var clock_link = document.createElement('a');51 clock_link.setAttribute('href', 'javascript:DateTimeShortcuts.openClock(' + num + ');');52 clock_link.id = DateTimeShortcuts.clockLinkName + num;53 quickElement('img', clock_link, '', 'src', DateTimeShortcuts.admin_media_prefix + 'img/icon_clock.gif', 'alt', gettext('Clock'));54 shortcuts_span.appendChild(document.createTextNode('\240'));55 shortcuts_span.appendChild(now_link);56 shortcuts_span.appendChild(document.createTextNode('\240|\240'));57 shortcuts_span.appendChild(clock_link);58 // Create clock link div59 //60 // Markup looks like:61 // <div id="clockbox1" class="clockbox module">62 // <h2>Choose a time</h2>63 // <ul class="timelist">64 // <li><a href="#">Now</a></li>65 // <li><a href="#">Midnight</a></li>66 // <li><a href="#">6 a.m.</a></li>67 // <li><a href="#">Noon</a></li>68 // </ul>69 // <p class="calendar-cancel"><a href="#">Cancel</a></p>70 // </div>71 var clock_box = document.createElement('div');72 clock_box.style.display = 'none';73 clock_box.style.position = 'absolute';74 clock_box.className = 'clockbox module';75 clock_box.setAttribute('id', DateTimeShortcuts.clockDivName + num);76 document.body.appendChild(clock_box);77 addEvent(clock_box, 'click', cancelEventPropagation);78 quickElement('h2', clock_box, gettext('Choose a time'));79 var time_list = quickElement('ul', clock_box, '');80 time_list.className = 'timelist';81 var time_format = get_format('TIME_INPUT_FORMATS')[0];82 quickElement("a", quickElement("li", time_list, ""), gettext("Now"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().strftime('" + time_format + "'));");83 quickElement("a", quickElement("li", time_list, ""), gettext("Midnight"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,0,0,0,0).strftime('" + time_format + "'));");84 quickElement("a", quickElement("li", time_list, ""), gettext("6 a.m."), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,6,0,0,0).strftime('" + time_format + "'));");85 quickElement("a", quickElement("li", time_list, ""), gettext("Noon"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date(1970,1,1,12,0,0,0).strftime('" + time_format + "'));");86 var cancel_p = quickElement('p', clock_box, '');87 cancel_p.className = 'calendar-cancel';88 quickElement('a', cancel_p, gettext('Cancel'), 'href', 'javascript:DateTimeShortcuts.dismissClock(' + num + ');');89 django.jQuery(document).bind('keyup', function(event) {90 if (event.which == 27) {91 // ESC key closes popup92 DateTimeShortcuts.dismissClock(num);93 event.preventDefault();94 }95 });96 },97 openClock: function(num) {98 var clock_box = document.getElementById(DateTimeShortcuts.clockDivName+num)99 var clock_link = document.getElementById(DateTimeShortcuts.clockLinkName+num)100 // Recalculate the clockbox position101 // is it left-to-right or right-to-left layout ?102 if (getStyle(document.body,'direction')!='rtl') {103 clock_box.style.left = findPosX(clock_link) + 17 + 'px';104 }105 else {106 // since style's width is in em, it'd be tough to calculate107 // px value of it. let's use an estimated px for now108 // TODO: IE returns wrong value for findPosX when in rtl mode109 // (it returns as it was left aligned), needs to be fixed.110 clock_box.style.left = findPosX(clock_link) - 110 + 'px';111 }112 clock_box.style.top = Math.max(0, findPosY(clock_link) - 30) + 'px';113 // Show the clock box114 clock_box.style.display = 'block';115 addEvent(document, 'click', DateTimeShortcuts.dismissClockFunc[num]);116 },117 dismissClock: function(num) {118 document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'none';119 removeEvent(document, 'click', DateTimeShortcuts.dismissClockFunc[num]);120 },121 handleClockQuicklink: function(num, val) {122 DateTimeShortcuts.clockInputs[num].value = val;123 DateTimeShortcuts.clockInputs[num].focus();124 DateTimeShortcuts.dismissClock(num);125 },126 // Add calendar widget to a given field.127 addCalendar: function(inp) {128 var num = DateTimeShortcuts.calendars.length;129 DateTimeShortcuts.calendarInputs[num] = inp;130 DateTimeShortcuts.dismissCalendarFunc[num] = function() { DateTimeShortcuts.dismissCalendar(num); return true; };131 // Shortcut links (calendar icon and "Today" link)132 var shortcuts_span = document.createElement('span');133 shortcuts_span.className = DateTimeShortcuts.shortCutsClass;134 inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling);135 var today_link = document.createElement('a');136 today_link.setAttribute('href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);');137 today_link.appendChild(document.createTextNode(gettext('Today')));138 var cal_link = document.createElement('a');139 cal_link.setAttribute('href', 'javascript:DateTimeShortcuts.openCalendar(' + num + ');');140 cal_link.id = DateTimeShortcuts.calendarLinkName + num;141 quickElement('img', cal_link, '', 'src', DateTimeShortcuts.admin_media_prefix + 'img/icon_calendar.gif', 'alt', gettext('Calendar'));142 shortcuts_span.appendChild(document.createTextNode('\240'));143 shortcuts_span.appendChild(today_link);144 shortcuts_span.appendChild(document.createTextNode('\240|\240'));145 shortcuts_span.appendChild(cal_link);146 // Create calendarbox div.147 //148 // Markup looks like:149 //150 // <div id="calendarbox3" class="calendarbox module">151 // <h2>152 // <a href="#" class="link-previous">&lsaquo;</a>153 // <a href="#" class="link-next">&rsaquo;</a> February 2003154 // </h2>155 // <div class="calendar" id="calendarin3">156 // <!-- (cal) -->157 // </div>158 // <div class="calendar-shortcuts">159 // <a href="#">Yesterday</a> | <a href="#">Today</a> | <a href="#">Tomorrow</a>160 // </div>161 // <p class="calendar-cancel"><a href="#">Cancel</a></p>162 // </div>163 var cal_box = document.createElement('div');164 cal_box.style.display = 'none';165 cal_box.style.position = 'absolute';166 cal_box.className = 'calendarbox module';167 cal_box.setAttribute('id', DateTimeShortcuts.calendarDivName1 + num);168 document.body.appendChild(cal_box);169 addEvent(cal_box, 'click', cancelEventPropagation);170 // next-prev links171 var cal_nav = quickElement('div', cal_box, '');172 var cal_nav_prev = quickElement('a', cal_nav, '<', 'href', 'javascript:DateTimeShortcuts.drawPrev('+num+');');173 cal_nav_prev.className = 'calendarnav-previous';174 var cal_nav_next = quickElement('a', cal_nav, '>', 'href', 'javascript:DateTimeShortcuts.drawNext('+num+');');175 cal_nav_next.className = 'calendarnav-next';176 // main box177 var cal_main = quickElement('div', cal_box, '', 'id', DateTimeShortcuts.calendarDivName2 + num);178 cal_main.className = 'calendar';179 DateTimeShortcuts.calendars[num] = new Calendar(DateTimeShortcuts.calendarDivName2 + num, DateTimeShortcuts.handleCalendarCallback(num));180 DateTimeShortcuts.calendars[num].drawCurrent();181 // calendar shortcuts182 var shortcuts = quickElement('div', cal_box, '');183 shortcuts.className = 'calendar-shortcuts';184 quickElement('a', shortcuts, gettext('Yesterday'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', -1);');185 shortcuts.appendChild(document.createTextNode('\240|\240'));186 quickElement('a', shortcuts, gettext('Today'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);');187 shortcuts.appendChild(document.createTextNode('\240|\240'));188 quickElement('a', shortcuts, gettext('Tomorrow'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', +1);');189 // cancel bar190 var cancel_p = quickElement('p', cal_box, '');191 cancel_p.className = 'calendar-cancel';192 quickElement('a', cancel_p, gettext('Cancel'), 'href', 'javascript:DateTimeShortcuts.dismissCalendar(' + num + ');');193 django.jQuery(document).bind('keyup', function(event) {194 if (event.which == 27) {195 // ESC key closes popup196 DateTimeShortcuts.dismissCalendar(num);197 event.preventDefault();198 }199 });200 },201 openCalendar: function(num) {202 var cal_box = document.getElementById(DateTimeShortcuts.calendarDivName1+num)203 var cal_link = document.getElementById(DateTimeShortcuts.calendarLinkName+num)204 var inp = DateTimeShortcuts.calendarInputs[num];205 // Determine if the current value in the input has a valid date.206 // If so, draw the calendar with that date's year and month.207 if (inp.value) {208 var date_parts = inp.value.split('-');209 var year = date_parts[0];210 var month = parseFloat(date_parts[1]);211 if (year.match(/\d\d\d\d/) && month >= 1 && month <= 12) {212 DateTimeShortcuts.calendars[num].drawDate(month, year);213 }214 }215 // Recalculate the clockbox position216 // is it left-to-right or right-to-left layout ?217 if (getStyle(document.body,'direction')!='rtl') {218 cal_box.style.left = findPosX(cal_link) + 17 + 'px';219 }220 else {221 // since style's width is in em, it'd be tough to calculate222 // px value of it. let's use an estimated px for now223 // TODO: IE returns wrong value for findPosX when in rtl mode224 // (it returns as it was left aligned), needs to be fixed.225 cal_box.style.left = findPosX(cal_link) - 180 + 'px';226 }227 cal_box.style.top = Math.max(0, findPosY(cal_link) - 75) + 'px';228 cal_box.style.display = 'block';229 addEvent(document, 'click', DateTimeShortcuts.dismissCalendarFunc[num]);230 },231 dismissCalendar: function(num) {232 document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'none';233 removeEvent(document, 'click', DateTimeShortcuts.dismissCalendarFunc[num]);234 },235 drawPrev: function(num) {236 DateTimeShortcuts.calendars[num].drawPreviousMonth();237 },238 drawNext: function(num) {239 DateTimeShortcuts.calendars[num].drawNextMonth();240 },241 handleCalendarCallback: function(num) {242 format = get_format('DATE_INPUT_FORMATS')[0];243 // the format needs to be escaped a little244 format = format.replace('\\', '\\\\');245 format = format.replace('\r', '\\r');246 format = format.replace('\n', '\\n');247 format = format.replace('\t', '\\t');248 format = format.replace("'", "\\'");249 return ["function(y, m, d) { DateTimeShortcuts.calendarInputs[",250 num,251 "].value = new Date(y, m-1, d).strftime('",252 format,253 "');DateTimeShortcuts.calendarInputs[",254 num,255 "].focus();document.getElementById(DateTimeShortcuts.calendarDivName1+",256 num,257 ").style.display='none';}"].join('');258 },259 handleCalendarQuickLink: function(num, offset) {260 var d = new Date();261 d.setDate(d.getDate() + offset)262 DateTimeShortcuts.calendarInputs[num].value = d.strftime(get_format('DATE_INPUT_FORMATS')[0]);263 DateTimeShortcuts.calendarInputs[num].focus();264 DateTimeShortcuts.dismissCalendar(num);265 }266}...

Full Screen

Full Screen

test-cron.js

Source:test-cron.js Github

copy

Full Screen

1var chai = require('chai'),2 expect = chai.expect,3 sinon = require('sinon'),4 cron = require('../lib/cron');5describe('cron', function() {6 it('should run every second (* * * * * *)', function() {7 var clock = sinon.useFakeTimers();8 var c = 0;9 var job = new cron.CronJob('* * * * * *', function() {10 c++;11 }, null, true);12 clock.tick(1000);13 job.stop();14 clock.restore();15 expect(c).to.eql(1);16 });17 it('should run second with oncomplete (* * * * * *)', function(done) {18 var clock = sinon.useFakeTimers();19 var c = 0;20 var job = new cron.CronJob('* * * * * *', function() {21 c++;22 }, function () {23 expect(c).to.eql(1);24 done();25 }, true);26 clock.tick(1000);27 clock.restore();28 job.stop();29 });30 it('should use standard cron no-seconds syntax (* * * * *)', function() {31 var clock = sinon.useFakeTimers();32 var c = 0;33 var job = new cron.CronJob('* * * * *', function() {34 c++;35 }, null, true);36 clock.tick(1000); //tick second37 clock.tick(59 * 1000); //tick minute38 job.stop();39 clock.restore();40 expect(c).to.eql(1);41 });42 it('should run every second for 5 seconds (* * * * * *)', function() {43 var clock = sinon.useFakeTimers();44 var c = 0;45 var job = new cron.CronJob('* * * * * *', function() {46 c++;47 }, null, true);48 for (var i = 0; i < 5; i++)49 clock.tick(1000);50 clock.restore();51 job.stop();52 expect(c).to.eql(5);53 });54 it('should run every second for 5 seconds with oncomplete (* * * * * *)', function(done) {55 var clock = sinon.useFakeTimers();56 var c = 0;57 var job = new cron.CronJob('* * * * * *', function() {58 c++;59 }, function() {60 expect(c).to.eql(5);61 done();62 }, true);63 for (var i = 0; i < 5; i++)64 clock.tick(1000);65 clock.restore();66 job.stop();67 });68 it('should run every second for 5 seconds (*/1 * * * * *)', function() {69 var clock = sinon.useFakeTimers();70 var c = 0;71 var job = new cron.CronJob('*/1 * * * * *', function() {72 c++;73 }, null, true);74 for (var i = 0; i < 5; i++)75 clock.tick(1000);76 clock.restore();77 job.stop();78 expect(c).to.eql(5);79 });80 //ensure that this is running on the second second81 it('should run every 2 seconds for 1 seconds (*/2 * * * * *)', function() {82 var clock = sinon.useFakeTimers();83 var c = 0;84 var job = new cron.CronJob('*/2 * * * * *', function() {85 c++;86 }, null, true);87 clock.tick(1000);88 clock.restore();89 job.stop();90 expect(c).to.eql(0);91 });92 it('should run every 2 seconds for 5 seconds (*/2 * * * * *)', function() {93 var clock = sinon.useFakeTimers();94 var c = 0;95 var job = new cron.CronJob('*/2 * * * * *', function() {96 c++;97 }, null, true);98 for (var i = 0; i < 5; i++)99 clock.tick(1000);100 clock.restore();101 job.stop();102 expect(c).to.eql(2);103 });104 it('should run every second for 5 seconds with oncomplete (*/1 * * * * *)', function(done) {105 var clock = sinon.useFakeTimers();106 var c = 0;107 var job = new cron.CronJob('*/1 * * * * *', function() {108 c++109 }, function() {110 expect(c).to.eql(5);111 done();112 }, true);113 for (var i = 0; i < 5; i++)114 clock.tick(1000);115 clock.restore();116 job.stop();117 });118 it('should run every second for a range ([start]-[end] * * * * *)', function() {119 var clock = sinon.useFakeTimers();120 var c = 0;121 var job = new cron.CronJob('0-8 * * * * *', function() {122 c++;123 }, null, true);124 clock.tick(10000); //run for 10 seconds125 clock.restore();126 job.stop();127 expect(c).to.eql(8);128 });129 it('should run every second for a range with oncomplete ([start]-[end] * * * * *)', function(done) {130 var clock = sinon.useFakeTimers();131 var c = 0;132 var job = new cron.CronJob('0-8 * * * * *', function() {133 c++;134 }, function() {135 expect(c).to.eql(8);136 done();137 }, true);138 clock.tick(10000);139 clock.restore();140 job.stop();141 });142 it('should run every second (* * * * * *) using the object constructor', function() {143 var clock = sinon.useFakeTimers();144 var c = 0;145 var job = new cron.CronJob({146 cronTime: '* * * * * *',147 onTick: function() {148 c++;149 },150 start: true151 });152 clock.tick(1000);153 clock.restore();154 job.stop();155 expect(c).to.eql(1);156 });157 it('should run every second with oncomplete (* * * * * *) using the object constructor', function(done) {158 var clock = sinon.useFakeTimers();159 var c = 0;160 var job = new cron.CronJob({161 cronTime: '* * * * * *',162 onTick: function(done) {163 c++;164 },165 onComplete: function () {166 expect(c).to.eql(1);167 done();168 },169 start: true170 });171 clock.tick(1000);172 clock.restore();173 job.stop();174 });175 it('should start and stop job', function(done) {176 var clock = sinon.useFakeTimers();177 var c = 0;178 var job = new cron.CronJob('* * * * * *', function() {179 c++;180 this.stop();181 }, function() {182 expect(c).to.eql(1);183 clock.restore();184 done();185 });186 job.start();187 clock.tick(1000);188 });189 it('should run on a specific date', function() {190 var c = 0;191 var d = new Date();192 var clock = sinon.useFakeTimers(d.getTime());193 var s = d.getSeconds()+1;194 d.setSeconds(s);195 var job = new cron.CronJob(d, function() {196 var t = new Date();197 expect(t.getSeconds()).to.eql(d.getSeconds());198 c++;199 }, null, true);200 clock.tick(1000);201 clock.restore();202 job.stop();203 expect(c).to.eql(1);204 });205 it('should run on a specific date with oncomplete', function(done) {206 var c = 0;207 var d = new Date();208 var clock = sinon.useFakeTimers(d.getTime());209 var s = d.getSeconds()+1;210 d.setSeconds(s);211 var job = new cron.CronJob(d, function() {212 var t = new Date();213 expect(t.getSeconds()).to.eql(d.getSeconds());214 c++;215 }, function() {216 expect(c).to.eql(1);217 done();218 }, true);219 clock.tick(1000);220 clock.restore();221 job.stop();222 });223 describe('with timezone', function() {224 it('should run a job using cron syntax', function () {225 var clock = sinon.useFakeTimers();226 var c = 0;227 var moment = require("moment-timezone");228 var zone = "America/Chicago";229 // New Orleans time230 var t = moment();231 t.tz(zone);232 // Current time233 d = moment();234 // If current time is New Orleans time, switch to Los Angeles..235 if (t.hours() === d.hours()) {236 zone = "America/Los_Angeles";237 t.tz(zone);238 }239 expect(d.hours()).to.not.eql(t.hours());240 // If t = 59s12m then t.setSeconds(60)241 // becones 00s13m so we're fine just doing242 // this and no testRun callback.243 t.add(1, 's');244 // Run a job designed to be executed at a given 245 // time in `zone`, making sure that it is a different246 // hour than local time.247 var job = new cron.CronJob(t.seconds() + ' ' + t.minutes() + ' ' + t.hours() + ' * * *', function(){248 c++;249 }, null, true, zone);250 clock.tick(1000);251 clock.restore();252 job.stop();253 expect(c).to.eql(1);254 });255 it('should run a job using a date', function () {256 var c = 0;257 var moment = require("moment-timezone");258 var zone = "America/Chicago";259 // New Orleans time260 var t = moment();261 t.tz(zone);262 // Current time263 d = moment();264 // If current time is New Orleans time, switch to Los Angeles..265 if (t.hours() === d.hours()) {266 zone = "America/Los_Angeles";267 t.tz(zone);268 }269 expect(d.hours()).to.not.eql(t.hours());270 d.add(1, 's');271 var clock = sinon.useFakeTimers(d._d.getTime());272 var job = new cron.CronJob(d._d, function() {273 c++;274 }, null, true, zone);275 clock.tick(1000);276 clock.restore();277 job.stop();278 expect(c).to.eql(1);279 });280 });281 it('should wait and not fire immediately', function() {282 var clock = sinon.useFakeTimers();283 var c = 0;284 var d = new Date().getTime() + 31 * 86400 * 1000;285 var job = cron.job(new Date(d), function() {286 c++;287 });288 job.start();289 clock.tick(1000);290 clock.restore();291 job.stop();292 expect(c).to.eql(0);293 });294 it('should start, change time, start again', function() {295 var c = 0;296 var clock = sinon.useFakeTimers();297 var job = new cron.CronJob('* * * * * *', function() {298 c++;299 });300 job.start();301 clock.tick(1000);302 job.stop();303 var time = cron.time('*/2 * * * * *');304 job.setTime(time);305 job.start();306 clock.tick(4000);307 clock.restore();308 job.stop();309 expect(c).to.eql(3);310 });311 it('should start, change time, exception', function() {312 var c = 0;313 var clock = sinon.useFakeTimers();314 var job = new cron.CronJob('* * * * * *', function() {315 c++;316 });317 var time = new Date();318 job.start();319 clock.tick(1000);320 job.stop();321 expect(function() {322 job.setTime(time);323 }).to.throw;324 clock.restore();325 job.stop();326 expect(c).to.eql(1);327 });328 it('should scope onTick to running job', function() {329 var clock = sinon.useFakeTimers();330 var job = new cron.CronJob('* * * * * *', function() {331 expect(job).to.be.instanceOf(cron.CronJob);332 expect(job).to.eql(this);333 }, null, true);334 clock.tick(1000);335 clock.restore();336 job.stop();337 });338 it('should scope onTick to object', function() {339 var clock = sinon.useFakeTimers();340 var job = new cron.CronJob('* * * * * *', function() {341 expect(this.hello).to.eql('world');342 expect(job).to.not.eql(this);343 }, null, true, null, {'hello':'world'});344 clock.tick(1000);345 clock.restore();346 job.stop();347 });348 it('should scope onTick to object within contstructor object', function() {349 var clock = sinon.useFakeTimers();350 var job = new cron.CronJob({351 cronTime: '* * * * * *',352 onTick: function() {353 expect(this.hello).to.eql('world');354 expect(job).to.not.eql(this);355 },356 start: true,357 context: {hello: 'world'}358 });359 clock.tick(1000);360 clock.restore();361 job.stop();362 });363 it('should not get into an infinite loop on invalid times', function() {364 var clock = sinon.useFakeTimers();365 var invalid1 = new cron.CronJob('* 60 * * * *', function() {366 assert.ok(true);367 }, null, true);368 var invalid2 = new cron.CronJob('* * 24 * * *', function() {369 assert.ok(true);370 }, null, true);371 clock.tick(1000);372 // assert that it gets here373 invalid1.stop();374 invalid2.stop();375 clock.restore();376 });377 it('should test start of month', function() {378 var c = 0;379 var d = new Date('12/31/2014');380 d.setSeconds(59);381 d.setMinutes(59);382 d.setHours(23);383 var clock = sinon.useFakeTimers(d.getTime());384 var job = new cron.CronJob('0 0 0 1 * *', function() {385 c++;386 }, null, true);387 clock.tick(1001);388 expect(c).to.eql(1);389 clock.tick(2678399001);390 expect(c).to.eql(1);391 clock.tick(2678400001); //jump over 2 firsts392 clock.restore();393 job.stop();394 expect(c).to.eql(3);395 });396 it('should run every second monday');...

Full Screen

Full Screen

jsUnitMockTimeout.js

Source:jsUnitMockTimeout.js Github

copy

Full Screen

1/**2 * @fileoverview3 * jsUnitMockTimeout.js changes the behavior of setTimeout, clearTimeout, setInterval and clearInterval to provide a4 * powerful way of testing callbacks. Instead of setting up timed callbacks, the callbacks and the time to their5 * execution are stored on a class called Clock. When the Clock is told to "advance time", the appropriate callbacks6 * are executed. In this way, real time is taken out of the picture and the test author has control.7 *8 * Contributed by Nathan Wilmes of Pivotal Labs, http://www.pivotallabs.com9 */1011/**12 * @class13 * Clock stores callbacks and executes them when it is told to simulate the advancing of time14 */15function Clock() { }16/**17 * The number of timeouts executed18 */19Clock.timeoutsMade = 0;20/**21 * Hash of milliseconds to scheduled functions22 */23Clock.scheduledFunctions = {};24/**25 * The current milliseconds26 */27Clock.nowMillis = 0;2829/**30 * Resets the clock - clears the scheduledFunctions, the current milliseconds, and the timeouts made count31 */32Clock.reset = function() {33 Clock.scheduledFunctions = {};34 Clock.nowMillis = 0;35 Clock.timeoutsMade = 0;36}3738/**39 * Simulate the advancing of time. Any functions scheduled in the given interval will be executed40 * @param millis the number of milliseconds by which to advance time41 */42Clock.tick = function(millis) {43 var oldMillis = Clock.nowMillis;44 var newMillis = oldMillis + millis;45 Clock._runFunctionsWithinRange(oldMillis, newMillis);46 Clock.nowMillis = newMillis;47};4849/**50 * @private51 * @param oldMillis52 * @param nowMillis53 */54Clock._runFunctionsWithinRange = function(oldMillis, nowMillis) {55 var scheduledFunc;56 var funcsToRun = [];57 for (var timeoutKey in Clock.scheduledFunctions) {58 scheduledFunc = Clock.scheduledFunctions[timeoutKey];59 if (scheduledFunc != undefined &&60 scheduledFunc.runAtMillis >= oldMillis &&61 scheduledFunc.runAtMillis <= nowMillis) {62 funcsToRun.push(scheduledFunc);63 Clock.scheduledFunctions[timeoutKey] = undefined;64 }65 }6667 if (funcsToRun.length > 0) {68 funcsToRun.sort(function(a, b) {69 return a.runAtMillis - b.runAtMillis;70 });71 for (var i = 0; i < funcsToRun.length; ++i) {72 try {73 Clock.nowMillis = funcsToRun[i].runAtMillis;74 funcsToRun[i].funcToCall();75 if (funcsToRun[i].recurring) {76 Clock.scheduleFunction(funcsToRun[i].timeoutKey,77 funcsToRun[i].funcToCall,78 funcsToRun[i].millis,79 true);80 }81 } catch(e) {82 }83 }84 Clock._runFunctionsWithinRange(oldMillis, nowMillis);85 }86}8788/**89 * Schedules a function to be executed at the given number of milliseconds from now90 * @param timeoutKey - the ID of the callback91 * @param funcToCall - the function to call92 * @param millis - the number of milliseconds before the callback93 * @param recurring - whether the callback recurs - if true, then the callback will be re-registered after it executes94 */95Clock.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) {96 Clock.scheduledFunctions[timeoutKey] = {97 runAtMillis: Clock.nowMillis + millis,98 funcToCall: funcToCall,99 recurring: recurring,100 timeoutKey: timeoutKey,101 millis: millis102 };103};104105/**106 * Mocks out setTimeout by registering the callback with Clock107 * @param funcToCall108 * @param millis109 * @return the ID of the timeout, which is the index of the scheduledFunction in Clock's list of scheduledFunctions110 */111function setTimeout(funcToCall, millis) {112 Clock.timeoutsMade = Clock.timeoutsMade + 1;113 Clock.scheduleFunction(Clock.timeoutsMade, funcToCall, millis, false);114 return Clock.timeoutsMade;115}116117/**118 * Mocks out setInterval by registering the callback with Clock119 * @param funcToCall120 * @param millis121 * @return the ID of the timeout, which is the index of the scheduledFunction in Clock's list of scheduledFunctions122 */123function setInterval(funcToCall, millis) {124 Clock.timeoutsMade = Clock.timeoutsMade + 1;125 Clock.scheduleFunction(Clock.timeoutsMade, funcToCall, millis, true);126 return Clock.timeoutsMade;127}128129/**130 * Mocks out clearTimeout by clearing Clock's scheduledFunction for the given ID131 */132function clearTimeout(timeoutKey) {133 Clock.scheduledFunctions[timeoutKey] = undefined;134}135136/**137 * Mocks out clearInterval by clearing Clock's scheduledFunction for the given ID138 */139function clearInterval(timeoutKey) {140 Clock.scheduledFunctions[timeoutKey] = undefined; ...

Full Screen

Full Screen

delay_test.js

Source:delay_test.js Github

copy

Full Screen

1// Copyright 2007 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14goog.provide('goog.async.DelayTest');15goog.setTestOnly('goog.async.DelayTest');16goog.require('goog.async.Delay');17goog.require('goog.testing.MockClock');18goog.require('goog.testing.jsunit');19var invoked = false;20var delay = null;21var clock = null;22function callback() {23 invoked = true;24}25function setUp() {26 clock = new goog.testing.MockClock(true);27 invoked = false;28 delay = new goog.async.Delay(callback, 200);29}30function tearDown() {31 clock.dispose();32 delay.dispose();33}34function testDelay() {35 delay.start();36 assertFalse(invoked);37 clock.tick(100);38 assertFalse(invoked);39 clock.tick(100);40 assertTrue(invoked);41}42function testStop() {43 delay.start();44 clock.tick(100);45 assertFalse(invoked);46 delay.stop();47 clock.tick(100);48 assertFalse(invoked);49}50function testIsActive() {51 assertFalse(delay.isActive());52 delay.start();53 assertTrue(delay.isActive());54 clock.tick(200);55 assertFalse(delay.isActive());56}57function testRestart() {58 delay.start();59 clock.tick(100);60 delay.stop();61 assertFalse(invoked);62 delay.start();63 clock.tick(199);64 assertFalse(invoked);65 clock.tick(1);66 assertTrue(invoked);67 invoked = false;68 delay.start();69 clock.tick(200);70 assertTrue(invoked);71}72function testStartIfNotActive() {73 delay.startIfNotActive();74 clock.tick(100);75 delay.stop();76 assertFalse(invoked);77 delay.startIfNotActive();78 clock.tick(199);79 assertFalse(invoked);80 clock.tick(1);81 assertTrue(invoked);82 invoked = false;83 delay.start();84 clock.tick(199);85 assertFalse(invoked);86 delay.startIfNotActive();87 clock.tick(1);88 assertTrue(invoked);89}90function testOverride() {91 delay.start(50);92 clock.tick(49);93 assertFalse(invoked);94 clock.tick(1);95 assertTrue(invoked);96}97function testDispose() {98 delay.start();99 delay.dispose();100 assertTrue(delay.isDisposed());101 clock.tick(500);102 assertFalse(invoked);103}104function testFire() {105 delay.start();106 clock.tick(50);107 delay.fire();108 assertTrue(invoked);109 assertFalse(delay.isActive());110 invoked = false;111 clock.tick(200);112 assertFalse('Delay fired early with fire call, timeout should have been ' +113 'cleared', invoked);114}115function testFireIfActive() {116 delay.fireIfActive();117 assertFalse(invoked);118 delay.start();119 delay.fireIfActive();120 assertTrue(invoked);121 invoked = false;122 clock.tick(300);123 assertFalse('Delay fired early with fireIfActive, timeout should have been ' +124 'cleared', invoked);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const clock = require('stryker-parent').clock;2const clock = require('stryker-parent').clock;3const clock = require('stryker-parent').clock;4const clock = require('stryker-parent').clock;5const clock = require('stryker-parent').clock;6const clock = require('stryker-parent').clock;7const clock = require('stryker-parent').clock;8const clock = require('stryker-parent').clock;9const clock = require('stryker-parent').clock;10const clock = require('stryker-parent').clock;11const clock = require('stryker-parent').clock;12const clock = require('stryker-parent').clock;13const clock = require('stryker-parent').clock;14const clock = require('stryker-parent').clock;15const clock = require('stryker-parent').clock;16const clock = require('stryker-parent').clock;17const clock = require('stryker-parent').clock;18const clock = require('stryker-parent').clock;19const clock = require('stryker-parent').clock;20const clock = require('stryker-parent').clock;

Full Screen

Using AI Code Generation

copy

Full Screen

1const clock = require('stryker-parent').clock;2const log = require('stryker-parent').log;3const clock = require('stryker-parent').clock;4const log = require('stryker-parent').log;5const clock = require('stryker-parent').clock;6const log = require('stryker-parent').log;7const clock = require('stryker-parent').clock;8const log = require('stryker-parent').log;9const clock = require('stryker-parent').clock;10const log = require('stryker-parent').log;11const clock = require('stryker-parent').clock;12const log = require('stryker-parent').log;13const clock = require('stryker-parent').clock;14const log = require('stryker-parent').log;15const clock = require('stryker-parent').clock;16const log = require('stryker-parent').log;17const clock = require('stryker-parent').clock;18const log = require('stryker-parent').log;19const clock = require('stryker-parent').clock;20const log = require('stryker-parent').log;21const clock = require('stryker-parent').clock;22const log = require('stryker-parent').log;

Full Screen

Using AI Code Generation

copy

Full Screen

1const clock = require('stryker-parent').clock;2const clock = require('stryker-parent').clock;3const clock = require('stryker-parent').clock;4const clock = require('stryker-parent').clock;5const clock = require('stryker-parent').clock;6const clock = require('stryker-parent').clock;7const clock = require('stryker-parent').clock;8const clock = require('stryker-parent').clock;9const clock = require('stryker-parent').clock;10const clock = require('stryker-parent').clock;11const clock = require('stryker-parent').clock;12const clock = require('stryker-parent').clock;13const clock = require('stryker-parent').clock;14const clock = require('stryker-parent').clock;15const clock = require('stryker-parent').clock;16const clock = require('stryker-parent').clock;17const clock = require('stryker-parent').clock;18const clock = require('stryker-parent').clock;19const clock = require('stryker-parent').clock;20const clock = require('stryker-parent

Full Screen

Using AI Code Generation

copy

Full Screen

1const clock = require('stryker-parent').clock;2const log = require('stryker-parent').log;3const test = require('stryker-parent').test;4const testRunner = require('stryker-parent').testRunner;5const testFramework = require('stryker-parent').testFramework;6const reporter = require('stryker-parent').reporter;7const coverageAnalysis = require('stryker-parent').coverageAnalysis;8const fs = require('fs');9const path = require('path');10const { expect } = require('chai');11const { TestStatus } = require('stryker-api/test_runner');12const { TestResult } = require('stryker-api/test_runner');13const { TestFramework, TestFrameworkFactory } = require('stryker-api/test_framework');14const { TestRunner, TestRunnerFactory } = require('stryker-api/test_runner');15const { Reporter, ReporterFactory } = require('stryker-api/report');16const { Config } = require('stryker-api/config');17const { expectTestResult } = require('./helpers/expectTestResult');18const { expectTestResults } = require('./helpers/expectTestResults');19const { runInFiberContext } = require('fibers');20const { TestStatus } = require('stryker-api/test_runner');

Full Screen

Using AI Code Generation

copy

Full Screen

1function clock () {2 return Date.now()3}4function clock () {5 return Date.now()6}7var clock = require('./stryker-parent').clock8var clock2 = require('./stryker-child').clock9function clock () {10 return Date.now()11}12function clock () {13 return Date.now()14}15var clock = require('./stryker-parent').clock16var clock2 = require('./stryker-child').clock

Full Screen

Using AI Code Generation

copy

Full Screen

1var clock = require('stryker-parent').clock;2clock.setSystemTime(2014, 10, 15);3var clock = require('stryker-parent').clock;4clock.setSystemTime(2014, 10, 15);5var clock = require('stryker-parent').clock;6clock.setSystemTime(2014, 10, 15);7var clock = require('stryker-parent').clock;8clock.setSystemTime(2014, 10, 15);9var clock = require('stryker-parent').clock;10clock.setSystemTime(2014, 10, 15);11var clock = require('stryker-parent').clock;12clock.setSystemTime(2014, 10, 15);13var clock = require('stryker-parent').clock;14clock.setSystemTime(2014, 10, 15);15var clock = require('stryker-parent').clock;16clock.setSystemTime(2014, 10, 15);17var clock = require('stryker-parent').clock;18clock.setSystemTime(2014, 10, 15);19var clock = require('stryker-parent').clock;20clock.setSystemTime(2014, 10, 15);21var clock = require('stryker-parent').clock;22clock.setSystemTime(2014, 10, 15);23var clock = require('stryker-parent').clock;24clock.setSystemTime(2014, 10, 15);

Full Screen

Using AI Code Generation

copy

Full Screen

1const clock = require('stryker-parent').clock;2describe('Demo', () => {3 it('should be able to mock the date', () => {4 clock.set(new Date(2016, 1, 1));5 expect(new Date().getMonth()).to.equal(1);6 });7});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run stryker-parent 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