jspec.js
This file
Path
spec/lib/jspec.js
1,776 lines · 51.2 KiB · JavaScript
Last changed by
Not known.
History of this fileTake it
12// JSpec - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34(function(){56 JSpec = {78 version : '2.11.13',9 cache : {},10 suites : [],11 modules : [],12 allSuites : [],13 matchers : {},14 stubbed : [],15 request : 'XMLHttpRequest' in this ? XMLHttpRequest : null,16 stats : { specs: 0, assertions: 0, failures: 0, passes: 0, specsFinished: 0, suitesFinished: 0 },17 options : { profile: false },1819 /**20 * Default context in which bodies are evaluated.21 *22 * Replace context simply by setting JSpec.context23 * to your own like below:24 *25 * JSpec.context = { foo : 'bar' }26 *27 * Contexts can be changed within any body, this can be useful28 * in order to provide specific helper methods to specific suites.29 *30 * To reset (usually in after hook) simply set to null like below:31 *32 * JSpec.context = null33 *34 */3536 defaultContext : {37 38 /**39 * Return an object used for proxy assertions. 40 * This object is used to indicate that an object41 * should be an instance of _object_, not the constructor42 * itself.43 *44 * @param {function} constructor45 * @return {hash}46 * @api public47 */48 49 an_instance_of : function(constructor) {50 return { an_instance_of : constructor }51 },52 53 /**54 * Load fixture at _path_. This utility function55 * supplies the means to resolve, and cache fixture contents56 * via the DOM or Rhino.57 *58 * Fixtures are resolved as:59 *60 * - <path>61 * - fixtures/<path>62 * - fixtures/<path>.html63 *64 * @param {string} path65 * @return {string}66 * @api public67 */68 69 fixture : function(path) {70 if (JSpec.cache[path]) return JSpec.cache[path]71 return JSpec.cache[path] = 72 JSpec.tryLoading(path) ||73 JSpec.tryLoading('fixtures/' + path) ||74 JSpec.tryLoading('fixtures/' + path + '.html') ||75 JSpec.tryLoading('spec/' + path) ||76 JSpec.tryLoading('spec/fixtures/' + path) ||77 JSpec.tryLoading('spec/fixtures/' + path + '.html')78 }79 },8081 // --- Objects82 83 formatters : {84 85 /**86 * Report to server.87 * 88 * Options:89 * - uri specific uri to report to.90 * - verbose weither or not to output messages91 * - failuresOnly output failure messages only92 *93 * @api public94 */95 96 Server : function(results, options) {97 var uri = options.uri || 'http://' + window.location.host + '/results'98 JSpec.post(uri, {99 stats: JSpec.stats,100 options: options,101 results: map(results.allSuites, function(suite) {102 if (suite.hasSpecs())103 return {104 description: suite.description,105 specs: map(suite.specs, function(spec) {106 return {107 description: spec.description,108 message: !spec.passed() ? spec.failure().message : null,109 status: spec.requiresImplementation() ? 'pending' :110 spec.passed() ? 'pass' :111 'fail',112 assertions: map(spec.assertions, function(assertion){113 return {114 passed: assertion.passed 115 }116 })117 }118 })119 }120 })121 })122 if ('close' in main) main.close()123 },124125 /**126 * Default formatter, outputting to the DOM.127 *128 * Options:129 * - reportToId id of element to output reports to, defaults to 'jspec'130 * - failuresOnly displays only suites with failing specs131 *132 * @api public133 */134135 DOM : function(results, options) {136 var id = option('reportToId') || 'jspec'137 var report = document.getElementById(id)138 var failuresOnly = option('failuresOnly')139 var classes = results.stats.failures ? 'has-failures' : ''140 if (!report) throw 'JSpec requires the element #' + id + ' to output its reports'141 142 function bodyContents(body) {143 return JSpec.144 escape(JSpec.contentsOf(body)).145 replace(/^ */gm, function(a){ return (new Array(Math.round(a.length / 3))).join(' ') }).146 replace(/\r\n|\r|\n/gm, '<br/>')147 }148 149 report.innerHTML = '<div id="jspec-report" class="' + classes + '"><div class="heading"> \150 <span class="passes">Passes: <em>' + results.stats.passes + '</em></span> \151 <span class="failures">Failures: <em>' + results.stats.failures + '</em></span> \152 </div><table class="suites">' + map(results.allSuites, function(suite) {153 var displaySuite = failuresOnly ? suite.ran && !suite.passed() : suite.ran154 if (displaySuite && suite.hasSpecs())155 return '<tr class="description"><td colspan="2">' + escape(suite.description) + '</td></tr>' +156 map(suite.specs, function(i, spec) {157 return '<tr class="' + (i % 2 ? 'odd' : 'even') + '">' +158 (spec.requiresImplementation() ?159 '<td class="requires-implementation" colspan="2">' + escape(spec.description) + '</td>' :160 (spec.passed() && !failuresOnly) ?161 '<td class="pass">' + escape(spec.description)+ '</td><td>' + spec.assertionsGraph() + '</td>' :162 !spec.passed() ?163 '<td class="fail">' + escape(spec.description) + 164 map(spec.failures(), function(a){ return '<em>' + escape(a.message) + '</em>' }).join('') +165 '</td><td>' + spec.assertionsGraph() + '</td>' :166 '') +167 '<tr class="body"><td colspan="2"><pre>' + bodyContents(spec.body) + '</pre></td></tr>'168 }).join('') + '</tr>'169 }).join('') + '</table></div>'170 },171 172 /**173 * Terminal formatter.174 *175 * @api public176 */177 178 Terminal : function(results, options) {179 failuresOnly = option('failuresOnly')180 print(color("\n Passes: ", 'bold') + color(results.stats.passes, 'green') + 181 color(" Failures: ", 'bold') + color(results.stats.failures, 'red') + "\n")182 183 function indent(string) {184 return string.replace(/^(.)/gm, ' $1')185 }186 187 each(results.allSuites, function(suite) {188 var displaySuite = failuresOnly ? suite.ran && !suite.passed() : suite.ran189 if (displaySuite && suite.hasSpecs()) {190 print(color(' ' + suite.description, 'bold'))191 each(suite.specs, function(spec){192 var assertionsGraph = inject(spec.assertions, '', function(graph, assertion){193 return graph + color('.', assertion.passed ? 'green' : 'red')194 })195 if (spec.requiresImplementation())196 print(color(' ' + spec.description, 'blue') + assertionsGraph)197 else if (spec.passed() && !failuresOnly)198 print(color(' ' + spec.description, 'green') + assertionsGraph)199 else if (!spec.passed())200 print(color(' ' + spec.description, 'red') + assertionsGraph + 201 "\n" + indent(map(spec.failures(), function(a){ return a.message }).join("\n")) + "\n")202 })203 print("")204 }205 })206 207 quit(results.stats.failures)208 },209210 /**211 * Console formatter.212 *213 * @api public214 */215216 Console : function(results, options) {217 console.log('')218 console.log('Passes: ' + results.stats.passes + ' Failures: ' + results.stats.failures)219 each(results.allSuites, function(suite) {220 if (suite.ran) {221 console.group(suite.description)222 each(suite.specs, function(spec){223 var assertionCount = spec.assertions.length + ':'224 if (spec.requiresImplementation())225 console.warn(spec.description)226 else if (spec.passed())227 console.log(assertionCount + ' ' + spec.description)228 else 229 console.error(assertionCount + ' ' + spec.description + ', ' + spec.failure().message)230 })231 console.groupEnd()232 }233 })234 }235 },236 237 Assertion : function(matcher, actual, expected, negate) {238 extend(this, {239 message: '',240 passed: false,241 actual: actual,242 negate: negate,243 matcher: matcher,244 expected: expected,245 246 // Report assertion results247 248 report : function() {249 this.passed ? JSpec.stats.passes++ : JSpec.stats.failures++250 return this251 },252 253 // Run the assertion254 255 run : function() {256 // TODO: remove unshifting 257 expected.unshift(actual)258 this.result = matcher.match.apply(this, expected)259 this.passed = negate ? !this.result : this.result260 if (!this.passed) this.message = matcher.message.call(this, actual, expected, negate, matcher.name)261 return this262 }263 })264 },265 266 ProxyAssertion : function(object, method, times, negate) {267 var self = this268 var old = object[method]269 270 // Proxy271 272 object[method] = function(){273 args = argumentsToArray(arguments)274 result = old.apply(object, args)275 self.calls.push({ args : args, result : result })276 return result277 }278 279 // Times280 281 this.times = {282 once : 1,283 twice : 2284 }[times] || times || 1285 286 extend(this, {287 calls: [],288 message: '',289 defer: true,290 passed: false,291 negate: negate,292 object: object,293 method: method,294 295 // Proxy return value296 297 and_return : function(result) {298 this.expectedResult = result299 return this300 },301 302 // Proxy arguments passed303 304 with_args : function() {305 this.expectedArgs = argumentsToArray(arguments)306 return this307 },308 309 // Check if any calls have failing results310 311 anyResultsFail : function() {312 return any(this.calls, function(call){313 return self.expectedResult.an_instance_of ?314 call.result.constructor != self.expectedResult.an_instance_of:315 hash(self.expectedResult) != hash(call.result)316 })317 },318 319 // Check if any calls have passing results320 321 anyResultsPass : function() {322 return any(this.calls, function(call){323 return self.expectedResult.an_instance_of ?324 call.result.constructor == self.expectedResult.an_instance_of:325 hash(self.expectedResult) == hash(call.result)326 })327 },328 329 // Return the passing result330 331 passingResult : function() {332 return this.anyResultsPass().result333 },334335 // Return the failing result336 337 failingResult : function() {338 return this.anyResultsFail().result339 },340 341 // Check if any arguments fail342 343 anyArgsFail : function() {344 return any(this.calls, function(call){345 return any(self.expectedArgs, function(i, arg){346 if (arg == null) return call.args[i] == null347 return arg.an_instance_of ?348 call.args[i].constructor != arg.an_instance_of:349 hash(arg) != hash(call.args[i])350 351 })352 })353 },354 355 // Check if any arguments pass356 357 anyArgsPass : function() {358 return any(this.calls, function(call){359 return any(self.expectedArgs, function(i, arg){360 return arg.an_instance_of ?361 call.args[i].constructor == arg.an_instance_of:362 hash(arg) == hash(call.args[i])363 364 })365 })366 },367 368 // Return the passing args369 370 passingArgs : function() {371 return this.anyArgsPass().args372 },373 374 // Return the failing args375 376 failingArgs : function() {377 return this.anyArgsFail().args378 },379 380 // Report assertion results381 382 report : function() {383 this.passed ? ++JSpec.stats.passes : ++JSpec.stats.failures384 return this385 },386 387 // Run the assertion388 389 run : function() {390 var methodString = 'expected ' + object.toString() + '.' + method + '()' + (negate ? ' not' : '' )391 392 function times(n) {393 return n > 2 ? n + ' times' : { 1: 'once', 2: 'twice' }[n]394 }395 396 if (this.expectedResult != null && (negate ? this.anyResultsPass() : this.anyResultsFail()))397 this.message = methodString + ' to return ' + puts(this.expectedResult) + 398 ' but ' + (negate ? 'it did' : 'got ' + puts(this.failingResult())) 399400 if (this.expectedArgs && (negate ? !this.expectedResult && this.anyArgsPass() : this.anyArgsFail()))401 this.message = methodString + ' to be called with ' + puts.apply(this, this.expectedArgs) +402 ' but was' + (negate ? '' : ' called with ' + puts.apply(this, this.failingArgs()))403404 if (negate ? !this.expectedResult && !this.expectedArgs && this.calls.length >= this.times : this.calls.length != this.times)405 this.message = methodString + ' to be called ' + times(this.times) + 406 ', but ' + (this.calls.length == 0 ? ' was not called' : ' was called ' + times(this.calls.length))407 408 if (!this.message.length) 409 this.passed = true410 411 return this412 }413 })414 },415 416 /**417 * Specification Suite block object.418 *419 * @param {string} description420 * @param {function} body421 * @api private422 */423424 Suite : function(description, body) {425 var self = this426 extend(this, {427 body: body,428 description: description,429 suites: [],430 specs: [],431 ran: false,432 hooks: { 'before' : [], 'after' : [], 'before_each' : [], 'after_each' : [] },433 434 // Add a spec to the suite435436 addSpec : function(description, body) {437 var spec = new JSpec.Spec(description, body)438 this.specs.push(spec)439 JSpec.stats.specs++ // TODO: abstract440 spec.suite = this441 },442443 // Add a hook to the suite444445 addHook : function(hook, body) {446 this.hooks[hook].push(body)447 },448449 // Add a nested suite450451 addSuite : function(description, body) {452 var suite = new JSpec.Suite(description, body)453 JSpec.allSuites.push(suite)454 suite.name = suite.description455 suite.description = this.description + ' ' + suite.description456 this.suites.push(suite)457 suite.suite = this458 },459460 // Invoke a hook in context to this suite461462 hook : function(hook) {463 if (this.suite) this.suite.hook(hook)464 each(this.hooks[hook], function(body) {465 JSpec.evalBody(body, "Error in hook '" + hook + "', suite '" + self.description + "': ")466 })467 },468469 // Check if nested suites are present470471 hasSuites : function() {472 return this.suites.length 473 },474475 // Check if this suite has specs476477 hasSpecs : function() {478 return this.specs.length479 },480481 // Check if the entire suite passed482483 passed : function() {484 return !any(this.specs, function(spec){485 return !spec.passed() 486 })487 }488 })489 },490 491 /**492 * Specification block object.493 *494 * @param {string} description495 * @param {function} body496 * @api private497 */498499 Spec : function(description, body) {500 extend(this, {501 body: body,502 description: description,503 assertions: [],504 505 // Add passing assertion506 507 pass : function(message) {508 this.assertions.push({ passed: true, message: message })509 ++JSpec.stats.passes510 },511 512 // Add failing assertion513 514 fail : function(message) {515 this.assertions.push({ passed: false, message: message })516 ++JSpec.stats.failures517 },518 519 // Run deferred assertions520 521 runDeferredAssertions : function() {522 each(this.assertions, function(assertion){523 if (assertion.defer) assertion.run().report(), hook('afterAssertion', assertion)524 })525 },526 527 // Find first failing assertion528529 failure : function() {530 return find(this.assertions, function(assertion){531 return !assertion.passed532 })533 },534535 // Find all failing assertions536537 failures : function() {538 return select(this.assertions, function(assertion){539 return !assertion.passed540 })541 },542543 // Weither or not the spec passed544545 passed : function() {546 return !this.failure()547 },548549 // Weither or not the spec requires implementation (no assertions)550551 requiresImplementation : function() {552 return this.assertions.length == 0553 },554555 // Sprite based assertions graph556557 assertionsGraph : function() {558 return map(this.assertions, function(assertion){559 return '<span class="assertion ' + (assertion.passed ? 'passed' : 'failed') + '"></span>'560 }).join('')561 }562 })563 },564 565 Module : function(methods) {566 extend(this, methods)567 },568 569 JSON : {570 571 /**572 * Generic sequences.573 */574 575 meta : {576 '\b' : '\\b',577 '\t' : '\\t',578 '\n' : '\\n',579 '\f' : '\\f',580 '\r' : '\\r',581 '"' : '\\"',582 '\\' : '\\\\'583 },584 585 /**586 * Escapable sequences.587 */588 589 escapable : /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,590 591 /**592 * JSON encode _object_.593 *594 * @param {mixed} object595 * @return {string}596 * @api private597 */598 599 encode : function(object) {600 var self = this601 if (object == undefined || object == null) return 'null'602 if (object === true) return 'true'603 if (object === false) return 'false'604 switch (typeof object) {605 case 'number': return object606 case 'string': return this.escapable.test(object) ?607 '"' + object.replace(this.escapable, function (a) {608 return typeof self.meta[a] === 'string' ? self.meta[a] :609 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4)610 }) + '"' :611 '"' + object + '"'612 case 'object': 613 if (object.constructor == Array)614 return '[' + map(object, function(val){615 return self.encode(val)616 }).join(', ') + ']'617 else if (object)618 return '{' + map(object, function(key, val){619 return self.encode(key) + ':' + self.encode(val)620 }).join(', ') + '}'621 }622 return 'null'623 }624 },625 626 // --- DSLs627 628 DSLs : {629 snake : {630 expect : function(actual){631 return JSpec.expect(actual)632 },633634 describe : function(description, body) {635 return JSpec.currentSuite.addSuite(description, body)636 },637638 it : function(description, body) {639 return JSpec.currentSuite.addSpec(description, body)640 },641642 before : function(body) {643 return JSpec.currentSuite.addHook('before', body)644 },645646 after : function(body) {647 return JSpec.currentSuite.addHook('after', body)648 },649650 before_each : function(body) {651 return JSpec.currentSuite.addHook('before_each', body)652 },653654 after_each : function(body) {655 return JSpec.currentSuite.addHook('after_each', body)656 },657 658 should_behave_like : function(description) {659 return JSpec.shareBehaviorsOf(description)660 }661 }662 },663664 // --- Methods665 666 /**667 * Check if _value_ is 'stop'. For use as a668 * utility callback function.669 *670 * @param {mixed} value671 * @return {bool}672 * @api public673 */674 675 haveStopped : function(value) {676 return value === 'stop'677 },678 679 /**680 * Include _object_ which may be a hash or Module instance.681 *682 * @param {has, Module} object683 * @return {JSpec}684 * @api public685 */686 687 include : function(object) {688 var module = object.constructor == JSpec.Module ? object : new JSpec.Module(object)689 this.modules.push(module)690 if ('init' in module) module.init()691 if ('utilities' in module) extend(this.defaultContext, module.utilities)692 if ('matchers' in module) this.addMatchers(module.matchers)693 if ('formatters' in module) extend(this.formatters, module.formatters)694 if ('DSLs' in module)695 each(module.DSLs, function(name, methods){696 JSpec.DSLs[name] = JSpec.DSLs[name] || {}697 extend(JSpec.DSLs[name], methods)698 })699 return this700 },701 702 /**703 * Add a module hook _name_, which is immediately704 * called per module with the _args_ given. An array of705 * hook return values is returned.706 *707 * @param {name} string708 * @param {...} args709 * @return {array}710 * @api private711 */712 713 hook : function(name, args) {714 args = argumentsToArray(arguments, 1)715 return inject(JSpec.modules, [], function(results, module){716 if (typeof module[name] == 'function')717 results.push(JSpec.evalHook(module, name, args))718 })719 },720 721 /**722 * Eval _module_ hook _name_ with _args_. Evaluates in context723 * to the module itself, JSpec, and JSpec.context.724 *725 * @param {Module} module726 * @param {string} name727 * @param {array} args728 * @return {mixed}729 * @api private730 */731 732 evalHook : function(module, name, args) {733 hook('evaluatingHookBody', module, name)734 try { return module[name].apply(module, args) }735 catch(e) { error('Error in hook ' + module.name + '.' + name + ': ', e) }736 },737 738 /**739 * Same as hook() however accepts only one _arg_ which is740 * considered immutable. This function passes the arg741 * to the first module, then passes the return value of the last742 * module called, to the following module. 743 *744 * @param {string} name745 * @param {mixed} arg746 * @return {mixed}747 * @api private748 */749 750 hookImmutable : function(name, arg) {751 return inject(JSpec.modules, arg, function(result, module){752 if (typeof module[name] == 'function')753 return JSpec.evalHook(module, name, [result])754 })755 },756 757 /**758 * Find a suite by its description or name.759 *760 * @param {string} description761 * @return {Suite}762 * @api private763 */764 765 findSuite : function(description) {766 return find(this.allSuites, function(suite){767 return suite.name == description || suite.description == description768 })769 },770 771 /**772 * Share behaviors (specs) of the given suite with773 * the current suite.774 *775 * @param {string} description776 * @api public777 */778 779 shareBehaviorsOf : function(description) {780 if (suite = this.findSuite(description)) this.copySpecs(suite, this.currentSuite)781 else throw 'failed to share behaviors. ' + puts(description) + ' is not a valid Suite name'782 },783 784 /**785 * Copy specs from one suite to another. 786 *787 * @param {Suite} fromSuite788 * @param {Suite} toSuite789 * @api public790 */791 792 copySpecs : function(fromSuite, toSuite) {793 each(fromSuite.specs, function(spec){794 spec.assertions = []795 toSuite.specs.push(spec)796 })797 },798 799 /**800 * Convert arguments to an array.801 *802 * @param {object} arguments803 * @param {int} offset804 * @return {array}805 * @api public806 */807 808 argumentsToArray : function(arguments, offset) {809 return Array.prototype.slice.call(arguments, offset || 0)810 },811 812 /**813 * Return ANSI-escaped colored string.814 *815 * @param {string} string816 * @param {string} color817 * @return {string}818 * @api public819 */820 821 color : function(string, color) {822 return "\u001B[" + {823 bold : 1,824 black : 30,825 red : 31,826 green : 32,827 yellow : 33,828 blue : 34,829 magenta : 35,830 cyan : 36,831 white : 37832 }[color] + 'm' + string + "\u001B[0m"833 },834 835 /**836 * Default matcher message callback.837 *838 * @api private839 */840 841 defaultMatcherMessage : function(actual, expected, negate, name) {842 return 'expected ' + puts(actual) + ' to ' + 843 (negate ? 'not ' : '') + 844 name.replace(/_/g, ' ') +845 ' ' + puts.apply(this, expected.slice(1))846 },847 848 /**849 * Normalize a matcher message.850 *851 * When no messge callback is present the defaultMatcherMessage852 * will be assigned, will suffice for most matchers.853 *854 * @param {hash} matcher855 * @return {hash}856 * @api public857 */858 859 normalizeMatcherMessage : function(matcher) {860 if (typeof matcher.message != 'function') 861 matcher.message = this.defaultMatcherMessage862 return matcher863 },864 865 /**866 * Normalize a matcher body867 * 868 * This process allows the following conversions until869 * the matcher is in its final normalized hash state.870 *871 * - '==' becomes 'actual == expected'872 * - 'actual == expected' becomes 'return actual == expected'873 * - function(actual, expected) { return actual == expected } becomes 874 * { match : function(actual, expected) { return actual == expected }}875 *876 * @param {mixed} body877 * @return {hash}878 * @api public879 */880 881 normalizeMatcherBody : function(body) {882 switch (body.constructor) {883 case String:884 if (captures = body.match(/^alias (\w+)/)) return JSpec.matchers[last(captures)]885 if (body.length < 4) body = 'actual ' + body + ' expected'886 return { match: function(actual, expected) { return eval(body) }} 887 888 case Function:889 return { match: body }890 891 default:892 return body893 }894 },895 896 /**897 * Get option value. This method first checks if898 * the option key has been set via the query string,899 * otherwise returning the options hash value.900 *901 * @param {string} key902 * @return {mixed}903 * @api public904 */905 906 option : function(key) {907 return (value = query(key)) !== null ? value :908 JSpec.options[key] || null909 },910911 /**912 * Generates a hash of the object passed.913 *914 * @param {object} object915 * @return {string}916 * @api private917 */918919 hash : function(object) {920 if (object == null) return 'null'921 if (object == undefined) return 'undefined'922 function serialize(prefix) {923 return inject(object, prefix + ':', function(buffer, key, value){924 return buffer += hash(value)925 })926 }927 switch (object.constructor) {928 case Array : return serialize('a')929 case RegExp: return 'r:' + object.toString()930 case Number: return 'n:' + object.toString()931 case String: return 's:' + object.toString()932 case Object: return 'o:' + inject(object, [], function(array, key, value){933 array.push([key, hash(value)])934 }).sort()935 default: return object.toString()936 }937 },938939 /**940 * Return last element of an array.941 *942 * @param {array} array943 * @return {object}944 * @api public945 */946947 last : function(array) {948 return array[array.length - 1]949 },950951 /**952 * Convert object(s) to a print-friend string.953 *954 * @param {...} object955 * @return {string}956 * @api public957 */958959 puts : function(object) {960 if (arguments.length > 1) {961 return map(argumentsToArray(arguments), function(arg){962 return puts(arg)963 }).join(', ')964 }965 if (object === undefined) return ''966 if (object === null) return 'null'967 if (object === true) return 'true'968 if (object === false) return 'false'969 if (object.an_instance_of) return 'an instance of ' + object.an_instance_of.name970 if (object.jquery && object.selector.length > 0) return 'selector ' + puts(object.selector) + ''971 if (object.jquery) return object.get(0).outerHTML972 if (object.nodeName) return object.outerHTML973 switch (object.constructor) {974 case String: return "'" + object + "'"975 case Number: return object976 case Function: return object.name || object 977 case Array: 978 return inject(object, '[', function(b, v){979 return b + ', ' + puts(v)980 }).replace('[,', '[') + ' ]'981 case Object:982 return inject(object, '{', function(b, k, v) {983 return b + ', ' + puts(k) + ' : ' + puts(v)984 }).replace('{,', '{') + ' }'985 default: 986 return object.toString()987 }988 },989990 /**991 * Escape HTML.992 *993 * @param {string} html994 * @return {string}995 * @api public996 */997998 escape : function(html) {999 return html.toString()1000 .replace(/&/gmi, '&')1001 .replace(/"/gmi, '"')1002 .replace(/>/gmi, '>')1003 .replace(/</gmi, '<')1004 },1005 1006 /**1007 * Perform an assertion without reporting.1008 *1009 * This method is primarily used for internal1010 * matchers in order retain DRYness. May be invoked 1011 * like below:1012 *1013 * does('foo', 'eql', 'foo')1014 * does([1,2], 'include', 1, 2)1015 *1016 * External hooks are not run for internal assertions1017 * performed by does().1018 *1019 * @param {mixed} actual1020 * @param {string} matcher1021 * @param {...} expected1022 * @return {mixed}1023 * @api private1024 */1025 1026 does : function(actual, matcher, expected) {1027 var assertion = new JSpec.Assertion(JSpec.matchers[matcher], actual, argumentsToArray(arguments, 2))1028 return assertion.run().result1029 },10301031 /**1032 * Perform an assertion.1033 *1034 * expect(true).to('be', true)1035 * expect('foo').not_to('include', 'bar')1036 * expect([1, [2]]).to('include', 1, [2])1037 *1038 * @param {mixed} actual1039 * @return {hash}1040 * @api public1041 */10421043 expect : function(actual) {1044 assert = function(matcher, args, negate) {1045 var expected = argumentsToArray(args, 1)1046 matcher.negate = negate 1047 assertion = new JSpec.Assertion(matcher, actual, expected, negate)1048 hook('beforeAssertion', assertion)1049 if (matcher.defer) assertion.run()1050 else JSpec.currentSpec.assertions.push(assertion.run().report()), hook('afterAssertion', assertion)1051 return assertion.result1052 }1053 1054 to = function(matcher) {1055 return assert(matcher, arguments, false)1056 }1057 1058 not_to = function(matcher) {1059 return assert(matcher, arguments, true)1060 }1061 1062 return {1063 to : to,1064 should : to,1065 not_to: not_to,1066 should_not : not_to1067 }1068 },10691070 /**1071 * Strim whitespace or chars.1072 *1073 * @param {string} string1074 * @param {string} chars1075 * @return {string}1076 * @api public1077 */10781079 strip : function(string, chars) {1080 return string.1081 replace(new RegExp('[' + (chars || '\\s') + ']*$'), '').1082 replace(new RegExp('^[' + (chars || '\\s') + ']*'), '')1083 },1084 1085 /**1086 * Call an iterator callback with arguments a, or b1087 * depending on the arity of the callback.1088 *1089 * @param {function} callback1090 * @param {mixed} a1091 * @param {mixed} b1092 * @return {mixed}1093 * @api private1094 */1095 1096 callIterator : function(callback, a, b) {1097 return callback.length == 1 ? callback(b) : callback(a, b)1098 },1099 1100 /**1101 * Extend an object with another.1102 *1103 * @param {object} object1104 * @param {object} other1105 * @api public1106 */1107 1108 extend : function(object, other) {1109 each(other, function(property, value){1110 object[property] = value1111 })1112 },1113 1114 /**1115 * Iterate an object, invoking the given callback.1116 *1117 * @param {hash, array, string} object1118 * @param {function} callback1119 * @return {JSpec}1120 * @api public1121 */11221123 each : function(object, callback) {1124 if (typeof object == 'string') object = object.split(' ')1125 for (key in object) 1126 if (object.hasOwnProperty(key))1127 callIterator(callback, key, object[key])1128 },11291130 /**1131 * Iterate with memo.1132 *1133 * @param {hash, array} object1134 * @param {object} memo1135 * @param {function} callback1136 * @return {object}1137 * @api public1138 */11391140 inject : function(object, memo, callback) {1141 each(object, function(key, value){1142 memo = (callback.length == 2 ?1143 callback(memo, value):1144 callback(memo, key, value)) ||1145 memo1146 })1147 return memo1148 },1149 1150 /**1151 * Destub _object_'s _method_. When no _method_ is passed1152 * all stubbed methods are destubbed. When no arguments1153 * are passed every object found in JSpec.stubbed will be1154 * destubbed.1155 *1156 * @param {mixed} object1157 * @param {string} method1158 * @api public1159 */1160 1161 destub : function(object, method) {1162 if (method) {1163 if (object['__prototype__' + method])1164 delete object[method]1165 else1166 object[method] = object['__original__' + method]1167 delete object['__prototype__' + method]1168 delete object['__original____' + method]1169 }1170 else if (object) {1171 for (var key in object)1172 if (captures = key.match(/^(?:__prototype__|__original__)(.*)/))1173 destub(object, captures[1])1174 }1175 else1176 while (JSpec.stubbed.length)1177 destub(JSpec.stubbed.shift())1178 },1179 1180 /**1181 * Stub _object_'s _method_. 1182 *1183 * stub(foo, 'toString').and_return('bar')1184 *1185 * @param {mixed} object1186 * @param {string} method1187 * @return {hash}1188 * @api public1189 */1190 1191 stub : function(object, method) {1192 hook('stubbing', object, method)1193 JSpec.stubbed.push(object)1194 var type = object.hasOwnProperty(method) ? '__original__' : '__prototype__'1195 object[type + method] = object[method]1196 object[method] = function(){}1197 return {1198 and_return : function(value) {1199 if (typeof value == 'function') object[method] = value1200 else object[method] = function(){ return value }1201 }1202 }1203 },1204 1205 /**1206 * Map callback return values.1207 *1208 * @param {hash, array} object1209 * @param {function} callback1210 * @return {array}1211 * @api public1212 */12131214 map : function(object, callback) {1215 return inject(object, [], function(memo, key, value){1216 memo.push(callIterator(callback, key, value))1217 })1218 },1219 1220 /**1221 * Returns the first matching expression or null.1222 *1223 * @param {hash, array} object1224 * @param {function} callback1225 * @return {mixed}1226 * @api public1227 */1228 1229 any : function(object, callback) {1230 return inject(object, null, function(state, key, value){1231 if (state == undefined)1232 return callIterator(callback, key, value) ? value : state1233 })1234 },1235 1236 /**1237 * Returns an array of values collected when the callback1238 * given evaluates to true.1239 *1240 * @param {hash, array} object1241 * @return {function} callback1242 * @return {array}1243 * @api public1244 */1245 1246 select : function(object, callback) {1247 return inject(object, [], function(selected, key, value){1248 if (callIterator(callback, key, value))1249 selected.push(value)1250 })1251 },12521253 /**1254 * Define matchers.1255 *1256 * @param {hash} matchers1257 * @api public1258 */12591260 addMatchers : function(matchers) {1261 each(matchers, function(name, body){1262 JSpec.addMatcher(name, body) 1263 })1264 },1265 1266 /**1267 * Define a matcher.1268 *1269 * @param {string} name1270 * @param {hash, function, string} body1271 * @api public1272 */1273 1274 addMatcher : function(name, body) {1275 hook('addingMatcher', name, body)1276 if (name.indexOf(' ') != -1) {1277 var matchers = name.split(/\s+/)1278 var prefix = matchers.shift()1279 each(matchers, function(name) {1280 JSpec.addMatcher(prefix + '_' + name, body(name))1281 })1282 }1283 this.matchers[name] = this.normalizeMatcherMessage(this.normalizeMatcherBody(body))1284 this.matchers[name].name = name1285 },1286 1287 /**1288 * Add a root suite to JSpec.1289 *1290 * @param {string} description1291 * @param {body} function1292 * @api public1293 */1294 1295 describe : function(description, body) {1296 var suite = new JSpec.Suite(description, body)1297 hook('addingSuite', suite)1298 this.allSuites.push(suite)1299 this.suites.push(suite)1300 },1301 1302 /**1303 * Return the contents of a function body.1304 *1305 * @param {function} body1306 * @return {string}1307 * @api public1308 */1309 1310 contentsOf : function(body) {1311 return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]1312 },13131314 /**1315 * Evaluate a JSpec capture body.1316 *1317 * @param {function} body1318 * @param {string} errorMessage (optional)1319 * @return {Type}1320 * @api private1321 */13221323 evalBody : function(body, errorMessage) {1324 var dsl = this.DSL || this.DSLs.snake1325 var matchers = this.matchers1326 var context = this.context || this.defaultContext1327 var contents = this.contentsOf(body)1328 hook('evaluatingBody', dsl, matchers, context, contents)1329 try { eval('with (dsl){ with (context) { with (matchers) { ' + contents + ' }}}') }1330 catch(e) { error(errorMessage, e) }1331 },13321333 /**1334 * Pre-process a string of JSpec.1335 *1336 * @param {string} input1337 * @return {string}1338 * @api private1339 */13401341 preprocess : function(input) {1342 if (typeof input != 'string') return1343 input = hookImmutable('preprocessing', input)1344 return input.1345 replace(/\t/g, ' ').1346 replace(/\r\n|\n|\r/g, '\n').1347 replace(/__END__[^]*/, '').1348 replace(/([\w\.]+)\.(stub|destub)\((.*?)\)$/gm, '$2($1, $3)').1349 replace(/describe\s+(.*?)$/gm, 'describe($1, function(){').1350 replace(/^\s+it\s+(.*?)$/gm, ' it($1, function(){').1351 replace(/^ *(before_each|after_each|before|after)(?= |\n|$)/gm, 'JSpec.currentSuite.addHook("$1", function(){').1352 replace(/^\s*end(?=\s|$)/gm, '});').1353 replace(/-\{/g, 'function(){').1354 replace(/(\d+)\.\.(\d+)/g, function(_, a, b){ return range(a, b) }).1355 replace(/\.should([_\.]not)?[_\.](\w+)(?: |;|$)(.*)$/gm, '.should$1_$2($3)').1356 replace(/([\/\s]*)(.+?)\.(should(?:[_\.]not)?)[_\.](\w+)\((.*)\)\s*;?$/gm, '$1 expect($2).$3($4, $5)').1357 replace(/, \)/g, ')').1358 replace(/should\.not/g, 'should_not')1359 },13601361 /**1362 * Create a range string which can be evaluated to a native array.1363 *1364 * @param {int} start1365 * @param {int} end1366 * @return {string}1367 * @api public1368 */13691370 range : function(start, end) {1371 var current = parseInt(start), end = parseInt(end), values = [current]1372 if (end > current) while (++current <= end) values.push(current)1373 else while (--current >= end) values.push(current)1374 return '[' + values + ']'1375 },13761377 /**1378 * Report on the results. 1379 *1380 * @api public1381 */13821383 report : function() {1384 hook('reporting', JSpec.options)1385 new (JSpec.options.formatter || JSpec.formatters.DOM)(JSpec, JSpec.options)1386 },13871388 /**1389 * Run the spec suites. Options are merged1390 * with JSpec options when present.1391 *1392 * @param {hash} options1393 * @return {JSpec}1394 * @api public1395 */13961397 run : function(options) {1398 if (any(hook('running'), haveStopped)) return this1399 if (options) extend(this.options, options)1400 if (option('profile')) console.group('Profile')1401 each(this.suites, function(suite) { JSpec.runSuite(suite) })1402 if (option('profile')) console.groupEnd()1403 return this1404 },1405 1406 /**1407 * Run a suite.1408 *1409 * @param {Suite} suite1410 * @api public1411 */14121413 runSuite : function(suite) {1414 this.currentSuite = suite1415 this.evalBody(suite.body)1416 suite.ran = true1417 hook('beforeSuite', suite), suite.hook('before')1418 each(suite.specs, function(spec) {1419 hook('beforeSpec', spec)1420 suite.hook('before_each')1421 JSpec.runSpec(spec)1422 hook('afterSpec', spec)1423 suite.hook('after_each')1424 })1425 if (suite.hasSuites()) {1426 each(suite.suites, function(suite) {1427 JSpec.runSuite(suite)1428 })1429 }1430 hook('afterSuite', suite), suite.hook('after')1431 this.stats.suitesFinished++1432 },1433 1434 /**1435 * Report a failure for the current spec.1436 *1437 * @param {string} message1438 * @api public1439 */1440 1441 fail : function(message) {1442 JSpec.currentSpec.fail(message)1443 },1444 1445 /**1446 * Report a passing assertion for the current spec.1447 *1448 * @param {string} message1449 * @api public1450 */1451 1452 pass : function(message) {1453 JSpec.currentSpec.pass(message)1454 },14551456 /**1457 * Run a spec.1458 *1459 * @param {Spec} spec1460 * @api public1461 */14621463 runSpec : function(spec) {1464 this.currentSpec = spec1465 if (option('profile')) console.time(spec.description)1466 try { this.evalBody(spec.body) }1467 catch (e) { fail(e) }1468 if (option('profile')) console.timeEnd(spec.description)1469 spec.runDeferredAssertions()1470 destub()1471 this.stats.specsFinished++1472 this.stats.assertions += spec.assertions.length1473 },14741475 /**1476 * Require a dependency, with optional message.1477 *1478 * @param {string} dependency1479 * @param {string} message (optional)1480 * @return {JSpec}1481 * @api public1482 */14831484 requires : function(dependency, message) {1485 hook('requiring', dependency, message)1486 try { eval(dependency) }1487 catch (e) { throw 'JSpec depends on ' + dependency + ' ' + message }1488 return this1489 },14901491 /**1492 * Query against the current query strings keys1493 * or the queryString specified.1494 *1495 * @param {string} key1496 * @param {string} queryString1497 * @return {string, null}1498 * @api private1499 */15001501 query : function(key, queryString) {1502 var queryString = (queryString || (main.location ? main.location.search : null) || '').substring(1)1503 return inject(queryString.split('&'), null, function(value, pair){1504 parts = pair.split('=')1505 return parts[0] == key ? parts[1].replace(/%20|\+/gmi, ' ') : value1506 })1507 },15081509 /**1510 * Throw a JSpec related error.1511 *1512 * @param {string} message1513 * @param {Exception} e1514 * @api public1515 */15161517 error : function(message, e) {1518 throw (message ? message : '') + e.toString() + 1519 (e.line ? ' near line ' + e.line : '')1520 },1521 1522 /**1523 * Ad-hoc POST request for JSpec server usage.1524 *1525 * @param {string} uri1526 * @param {string} data1527 * @api private1528 */1529 1530 post : function(uri, data) {1531 if (any(hook('posting', uri, data), haveStopped)) return1532 var request = this.xhr()1533 request.open('POST', uri, false)1534 request.setRequestHeader('Content-Type', 'application/json')1535 request.send(JSpec.JSON.encode(data))1536 },15371538 /**1539 * Instantiate an XMLHttpRequest.1540 *1541 * Here we utilize IE's lame ActiveXObjects first which1542 * allow IE access serve files via the file: protocol, otherwise1543 * we then default to XMLHttpRequest.1544 *1545 * @return {XMLHttpRequest, ActiveXObject}1546 * @api private1547 */1548 1549 xhr : function() {1550 return this.ieXhr() || new JSpec.request1551 },1552 1553 /**1554 * Return Microsoft piece of crap ActiveXObject.1555 *1556 * @return {ActiveXObject}1557 * @api public1558 */1559 1560 ieXhr : function() {1561 function object(str) {1562 try { return new ActiveXObject(str) } catch(e) {}1563 }1564 return object('Msxml2.XMLHTTP.6.0') ||1565 object('Msxml2.XMLHTTP.3.0') ||1566 object('Msxml2.XMLHTTP') ||1567 object('Microsoft.XMLHTTP')1568 },1569 1570 /**1571 * Check for HTTP request support.1572 *1573 * @return {bool}1574 * @api private1575 */1576 1577 hasXhr : function() {1578 return JSpec.request || 'ActiveXObject' in main1579 },1580 1581 /**1582 * Try loading _file_ returning the contents1583 * string or null. Chain to locate / read a file.1584 *1585 * @param {string} file1586 * @return {string}1587 * @api public1588 */1589 1590 tryLoading : function(file) {1591 try { return JSpec.load(file) }1592 catch (e) {}1593 },15941595 /**1596 * Load a _file_'s contents.1597 *1598 * @param {string} file1599 * @param {function} callback1600 * @return {string}1601 * @api public1602 */16031604 load : function(file, callback) {1605 if (any(hook('loading', file), haveStopped)) return1606 if ('readFile' in main)1607 return readFile(file)1608 else if (this.hasXhr()) {1609 var request = this.xhr()1610 request.open('GET', file, false)1611 request.send(null)1612 if (request.readyState == 4 && 1613 (request.status == 0 || 1614 request.status.toString().charAt(0) == 2)) 1615 return request.responseText1616 }1617 else1618 error("failed to load `" + file + "'")1619 },16201621 /**1622 * Load, pre-process, and evaluate a file.1623 *1624 * @param {string} file1625 * @param {JSpec}1626 * @api public1627 */16281629 exec : function(file) {1630 if (any(hook('executing', file), haveStopped)) return this1631 eval('with (JSpec){' + this.preprocess(this.load(file)) + '}')1632 return this1633 }1634 }16351636 // --- Utility functions16371638 var main = this1639 var find = JSpec.any1640 var utils = 'haveStopped stub hookImmutable hook destub map any last pass fail range each option inject select \1641 error escape extend puts hash query strip color does addMatchers callIterator argumentsToArray'.split(/\s+/)1642 while (utils.length) util = utils.shift(), eval('var ' + util + ' = JSpec.' + util)1643 if (!main.setTimeout) main.setTimeout = function(callback){ callback() }16441645 // --- Matchers16461647 addMatchers({1648 equal : "===",1649 be : "alias equal",1650 be_greater_than : ">",1651 be_less_than : "<",1652 be_at_least : ">=",1653 be_at_most : "<=",1654 be_a : "actual.constructor == expected",1655 be_an : "alias be_a",1656 be_an_instance_of : "actual instanceof expected",1657 be_null : "actual == null",1658 be_true : "actual == true",1659 be_false : "actual == false",1660 be_undefined : "typeof actual == 'undefined'",1661 be_type : "typeof actual == expected",1662 match : "typeof actual == 'string' ? actual.match(expected) : false",1663 respond_to : "typeof actual[expected] == 'function'",1664 have_length : "actual.length == expected",1665 be_within : "actual >= expected[0] && actual <= last(expected)",1666 have_length_within : "actual.length >= expected[0] && actual.length <= last(expected)",16671668 eql : function(actual, expected) {1669 return actual.constructor == Array ||1670 actual instanceof Object ? 1671 hash(actual) == hash(expected):1672 actual == expected1673 },1674 1675 receive : { defer : true, match : function(actual, method, times) {1676 proxy = new JSpec.ProxyAssertion(actual, method, times, this.negate)1677 JSpec.currentSpec.assertions.push(proxy)1678 return proxy1679 }},1680 1681 be_empty : function(actual) {1682 if (actual.constructor == Object && actual.length == undefined)1683 for (var key in actual)1684 return false;1685 return !actual.length1686 },16871688 include : function(actual) {1689 for (state = true, i = 1; i < arguments.length; i++) {1690 arg = arguments[i]1691 switch (actual.constructor) {1692 case String: 1693 case Number:1694 case RegExp:1695 case Function:1696 state = actual.toString().match(arg.toString())1697 break1698 1699 case Object:1700 state = arg in actual1701 break1702 1703 case Array: 1704 state = any(actual, function(value){ return hash(value) == hash(arg) })1705 break1706 }1707 if (!state) return false1708 }1709 return true1710 },17111712 throw_error : { match : function(actual, expected, message) {1713 try { actual() }1714 catch (e) {1715 this.e = e1716 var assert = function(arg) {1717 switch (arg.constructor) {1718 case RegExp : return arg.test(e)1719 case String : return arg == (e.message || e.toString())1720 case Function : return (e.name || 'Error') == arg.name1721 }1722 }1723 return message ? assert(expected) && assert(message) :1724 expected ? assert(expected) :1725 true1726 }1727 }, message : function(actual, expected, negate) {1728 // TODO: refactor when actual is not in expected [0]1729 var message_for = function(i) {1730 if (expected[i] == undefined) return 'exception'1731 switch (expected[i].constructor) {1732 case RegExp : return 'exception matching ' + puts(expected[i])1733 case String : return 'exception of ' + puts(expected[i])1734 case Function : return expected[i].name || 'Error'1735 }1736 }1737 exception = message_for(1) + (expected[2] ? ' and ' + message_for(2) : '')1738 return 'expected ' + exception + (negate ? ' not ' : '' ) +1739 ' to be thrown, but ' + (this.e ? 'got ' + puts(this.e) : 'nothing was')1740 }},1741 1742 have : function(actual, length, property) {1743 return actual[property].length == length1744 },1745 1746 have_at_least : function(actual, length, property) {1747 return actual[property].length >= length1748 },1749 1750 have_at_most :function(actual, length, property) {1751 return actual[property].length <= length1752 },1753 1754 have_within : function(actual, range, property) {1755 length = actual[property].length1756 return length >= range.shift() && length <= range.pop()1757 },1758 1759 have_prop : function(actual, property, value) {1760 return actual[property] == null || 1761 actual[property] instanceof Function ? false:1762 value == null ? true:1763 does(actual[property], 'eql', value)1764 },1765 1766 have_property : function(actual, property, value) {1767 return actual[property] == null ||1768 actual[property] instanceof Function ? false:1769 value == null ? true:1770 value === actual[property]1771 }1772 })1773 1774 if ('exports' in main) exports.JSpec = JSpec17751776})()