dwf: monster file re-org. RED BUILD

This commit is contained in:
Davis W. Frank
2009-06-14 23:34:29 -07:00
parent e48c22ffbd
commit b2cbff3bb6
17 changed files with 107 additions and 4399 deletions

50
spec/bootstrap.html Executable file
View File

@@ -0,0 +1,50 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Tests</title>
<script type="text/javascript" src="lib/json2.js"></script>
<script type="text/javascript" src="lib/mock-timeout.js"></script>
<script type="text/javascript" src="../lib/jsUnitMockTimeout.js"></script>
<script type="text/javascript" src="../src/base.js"></script>
<script type="text/javascript" src="../src/util.js"></script>
<script type="text/javascript" src="../src/Env.js"></script>
<script type="text/javascript" src="../src/ActionCollection.js"></script>
<script type="text/javascript" src="../src/Matchers.js"></script>
<script type="text/javascript" src="../src/NestedResults.js"></script>
<script type="text/javascript" src="../src/PrettyPrinter.js"></script>
<script type="text/javascript" src="../src/QueuedFunction.js"></script>
<script type="text/javascript" src="../src/Reporters.js"></script>
<script type="text/javascript" src="../src/Runner.js"></script>
<script type="text/javascript" src="../src/Spec.js"></script>
<script type="text/javascript" src="../src/Suite.js"></script>
<script type="text/javascript" src="../lib/json_reporter.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<link type="text/css" rel="stylesheet" href="../lib/jasmine.css"/>
</head>
<body onLoad="runTests();">
<h1>
Running all Jasmine Test Suites
</h1>
<div id="icon_wrapper">
<span id="icons"></span>
<img id="spinner" src="../images/spinner.gif" alt="" />
</div>
<div id="report">
<div id="results_summary" style="display:none;">
<h2>Summary</h2>
</div>
<div id="fails" style="display:none;">
<h2 id="fails_header">Failure Messages</h2>
<div id="fail_messages"></div>
</div>
</div>
<div style="display:none" id="json_reporter_results"></div>
<div style="display:none" id="json_reporter_results_incremental"></div>
</body>
</html>

297
spec/bootstrap.js vendored Executable file
View File

@@ -0,0 +1,297 @@
var createElement = function(tag, attrs) {
var element = document.createElement(tag);
for (var attr in attrs) {
element[attr] = attrs[attr];
}
return element;
};
// Bootstrap Test Reporter function
var Reporter = function () {
this.total = 0;
this.passes = 0;
this.fails = 0;
this.start = new Date();
};
Reporter.prototype.toJSON = function(object) {
return JSON.stringify(object);
};
Reporter.prototype.test = function (result, message) {
this.total++;
if (result) {
this.passes++;
iconElement = document.getElementById('icons');
iconElement.appendChild(createElement('img', {src: '../images/go-16.png'}));
}
else {
this.fails++;
var fails_report = document.getElementById('fails');
fails_report.style.display = "";
var iconElement = document.getElementById('icons');
iconElement.appendChild(createElement('img', {src: '../images/fail-16.png'}));
var failMessages = document.getElementById('fail_messages');
var newFail = createElement('p', {'class': 'fail'});
newFail.innerHTML = message;
failMessages.appendChild(newFail);
}
};
Reporter.prototype.summary = function () {
var el = createElement('p', {'class': ((this.fails > 0) ? 'fail_in_summary' : '') });
el.innerHTML = this.total + ' expectations, ' + this.passes + ' passing, ' + this.fails + ' failed in ' + (new Date().getTime() - this.start.getTime()) + "ms.";
var summaryElement = document.getElementById('results_summary');
summaryElement.appendChild(el);
summaryElement.style.display = "";
};
var reporter = new Reporter();
function runSuite(filename) {
var suite = jasmine.include(filename);
suite.execute();
emitSuiteResults(filename, suite);
}
function emitSpecResults(testName, spec) {
var results = spec.results.getItems();
reporter.test(results.length > 0, testName + ": should have results, got " + results.length);
for (var i = 0; i < results.length; i++) {
reporter.test(results[i].passed === true, testName + ':' + spec.getFullName() + ": expectation number " + i + " failed: " + results[i].message);
}
}
function emitSuiteResults(testName, suite) {
for (var j = 0; j < suite.specs.length; j++) {
var specOrSuite = suite.specs[j];
if (specOrSuite instanceof jasmine.Suite) {
emitSuiteResults(testName, specOrSuite);
} else {
emitSpecResults(testName, specOrSuite);
}
}
}
var testExplodes = function () {
var suite = describe('exploding', function () {
it('should throw an exception when this.explodes is called inside a spec', function() {
var exceptionMessage = false;
try {
this.explodes();
}
catch (e) {
exceptionMessage = e;
}
expect(exceptionMessage).toEqual('explodes function should not have been called');
});
});
suite.execute();
emitSuiteResults('testExplodes', suite);
};
function newJasmineEnv() {
return new jasmine.Env();
}
var testRunner = function() {
};
var testRunnerFinishCallback = function () {
var env = newJasmineEnv();
var foo = 0;
env.currentRunner.finish();
reporter.test((env.currentRunner.finished === true),
"Runner finished flag was not set.");
env.currentRunner.finishCallback = function () {
foo++;
};
env.currentRunner.finish();
reporter.test((env.currentRunner.finished === true),
"Runner finished flag was not set.");
reporter.test((foo === 1),
"Runner finish callback was not called");
};
var testHandlesBlankSpecs = function () {
var env = newJasmineEnv();
env.describe('Suite for handles blank specs', function () {
env.it('should be a test with a blank runs block', function() {
this.runs(function () {
});
});
env.it('should be a blank (empty function) test', function() {
});
});
var runner = env.currentRunner;
runner.execute();
reporter.test((runner.suites[0].results.getItems().length === 2),
'Should have found 2 spec results, got ' + runner.suites[0].results.getItems().length);
reporter.test((runner.suites[0].results.passedCount === 2),
'Should have found 2 passing specs, got ' + runner.suites[0].results.passedCount);
};
var testFormatsExceptionMessages = function () {
var sampleFirefoxException = {
fileName: 'foo.js',
line: '1978',
message: 'you got your foo in my bar',
name: 'A Classic Mistake'
};
var sampleWebkitException = {
sourceURL: 'foo.js',
lineNumber: '1978',
message: 'you got your foo in my bar',
name: 'A Classic Mistake'
};
var expected = 'A Classic Mistake: you got your foo in my bar in foo.js (line 1978)';
reporter.test((jasmine.util.formatException(sampleFirefoxException) === expected),
'Should have got ' + expected + ' but got: ' + jasmine.util.formatException(sampleFirefoxException));
reporter.test((jasmine.util.formatException(sampleWebkitException) === expected),
'Should have got ' + expected + ' but got: ' + jasmine.util.formatException(sampleWebkitException));
};
var testHandlesExceptions = function () {
var env = newJasmineEnv();
//we run two exception tests to make sure we continue after throwing an exception
var suite = env.describe('Suite for handles exceptions', function () {
env.it('should be a test that fails because it throws an exception', function() {
this.runs(function () {
throw new Error('fake error 1');
});
});
env.it('should be another test that fails because it throws an exception', function() {
this.runs(function () {
throw new Error('fake error 2');
});
this.runs(function () {
this.expect(true).toEqual(true);
});
});
env.it('should be a passing test that runs after exceptions are thrown', function() {
this.runs(function () {
this.expect(true).toEqual(true);
});
});
env.it('should be another test that fails because it throws an exception after a wait', function() {
this.runs(function () {
var foo = 'foo';
});
this.waits(250);
this.runs(function () {
throw new Error('fake error 3');
});
});
env.it('should be a passing test that runs after exceptions are thrown from a async test', function() {
this.runs(function () {
this.expect(true).toEqual(true);
});
});
});
var runner = env.currentRunner;
runner.execute();
Clock.tick(400); //TODO: setting this to a large number causes failures, but shouldn't
var resultsForSpec0 = suite.specs[0].getResults();
var resultsForSpec1 = suite.specs[1].getResults();
var resultsForSpec2 = suite.specs[2].getResults();
var resultsForSpec3 = suite.specs[3].getResults();
reporter.test((suite.getResults().totalCount == 6),
'Should have found 5 spec results, got ' + suite.getResults().totalCount);
reporter.test((resultsForSpec0.getItems()[0].passed === false),
'Spec1 test, expectation 0 should have failed, got passed');
reporter.test((resultsForSpec0.getItems()[0].message.match(/fake error 1/)),
'Spec1 test, expectation 0 should have a message that contained /fake error 1/, got ' + resultsForSpec0.getItems()[0].message);
reporter.test((resultsForSpec1.getItems()[0].passed === false),
'Spec2 test, expectation 0 should have failed, got passed');
reporter.test((resultsForSpec1.getItems()[0].message.match(/fake error 2/)),
'Spec2 test, expectation 0 should have a message that contained /fake error 2/, got ' + resultsForSpec1.getItems()[0].message);
reporter.test((resultsForSpec1.getItems()[1].passed === true),
'Spec2 test should have had a passing 2nd expectation');
reporter.test((resultsForSpec2.getItems()[0].passed === true),
'Spec3 test should have passed, got failed');
reporter.test((resultsForSpec3.getItems()[0].passed === false),
'Spec3 test should have a failing first expectation, got passed');
reporter.test((resultsForSpec3.getItems()[0].message.match(/fake error 3/)),
'Spec3 test should have an error message that contained /fake error 3/, got ' + resultsForSpec3.getItems()[0].message);
};
var testResultsAliasing = function () {
var env = newJasmineEnv();
env.describe('Suite for result aliasing test', function () {
env.it('should be a test', function() {
this.runs(function () {
this.expect(true).toEqual(true);
});
});
});
};
var runTests = function () {
document.getElementById('spinner').style.display = "";
runSuite('PrettyPrintTest.js');
runSuite('MatchersTest.js');
runSuite('SpecRunningTest.js');
runSuite('NestedResultsTest.js');
runSuite('ReporterTest.js');
runSuite('RunnerTest.js');
runSuite('JsonReporterTest.js');
runSuite('SpyTest.js');
testRunnerFinishCallback();
testFormatsExceptionMessages();
testHandlesExceptions();
testResultsAliasing();
// handle blank specs will work later.
// testHandlesBlankSpecs();
reporter.summary();
document.getElementById('spinner').style.display = "none";
};

478
spec/lib/json2.js Normal file
View File

@@ -0,0 +1,478 @@
/*
http://www.JSON.org/json2.js
2008-11-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the object holding the key.
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
*/
/*jslint evil: true */
/*global JSON */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (!this.JSON) {
JSON = {};
}
(function () {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ?
'"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' :
gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' :
gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
})();

158
spec/lib/mock-timeout.js Executable file
View File

@@ -0,0 +1,158 @@
// Mock setTimeout, clearTimeout
// Contributed by Pivotal Computer Systems, www.pivotalsf.com
jasmine.FakeTimer = function() {
this.reset();
var self = this;
self.setTimeout = function(funcToCall, millis) {
self.timeoutsMade++;
self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false);
return self.timeoutsMade;
};
self.setInterval = function(funcToCall, millis) {
self.timeoutsMade++;
self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true);
return self.timeoutsMade;
};
self.clearTimeout = function(timeoutKey) {
self.scheduledFunctions[timeoutKey] = undefined;
};
self.clearInterval = function(timeoutKey) {
self.scheduledFunctions[timeoutKey] = undefined;
};
};
jasmine.FakeTimer.prototype.reset = function() {
this.timeoutsMade = 0;
this.scheduledFunctions = {};
this.nowMillis = 0;
};
jasmine.FakeTimer.prototype.tick = function(millis) {
var oldMillis = this.nowMillis;
var newMillis = oldMillis + millis;
this.runFunctionsWithinRange(oldMillis, newMillis);
this.nowMillis = newMillis;
};
jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) {
var scheduledFunc;
var funcsToRun = [];
for (var timeoutKey in this.scheduledFunctions) {
scheduledFunc = this.scheduledFunctions[timeoutKey];
if (scheduledFunc != undefined &&
scheduledFunc.runAtMillis >= oldMillis &&
scheduledFunc.runAtMillis <= nowMillis) {
funcsToRun.push(scheduledFunc);
this.scheduledFunctions[timeoutKey] = undefined;
}
}
if (funcsToRun.length > 0) {
funcsToRun.sort(function(a, b) {
return a.runAtMillis - b.runAtMillis;
});
for (var i = 0; i < funcsToRun.length; ++i) {
try {
var funcToRun = funcsToRun[i];
this.nowMillis = funcToRun.runAtMillis;
funcToRun.funcToCall();
if (funcToRun.recurring) {
this.scheduleFunction(funcToRun.timeoutKey,
funcToRun.funcToCall,
funcToRun.millis,
true);
}
} catch(e) {
}
}
this.runFunctionsWithinRange(oldMillis, nowMillis);
}
};
jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) {
this.scheduledFunctions[timeoutKey] = {
runAtMillis: this.nowMillis + millis,
funcToCall: funcToCall,
recurring: recurring,
timeoutKey: timeoutKey,
millis: millis
};
};
jasmine.Clock = {
defaultFakeTimer: new jasmine.FakeTimer(),
reset: function() {
jasmine.Clock.assertInstalled();
jasmine.Clock.defaultFakeTimer.reset();
},
tick: function(millis) {
jasmine.Clock.assertInstalled();
jasmine.Clock.defaultFakeTimer.tick(millis);
},
runFunctionsWithinRange: function(oldMillis, nowMillis) {
jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis);
},
scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) {
jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring);
},
useMock: function() {
var spec = jasmine.getEnv().currentSpec;
spec.after(jasmine.Clock.uninstallMock);
jasmine.Clock.installMock();
},
installMock: function() {
jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer;
},
uninstallMock: function() {
jasmine.Clock.assertInstalled();
jasmine.Clock.installed = jasmine.Clock.real;
},
real: {
setTimeout: window.setTimeout,
clearTimeout: window.clearTimeout,
setInterval: window.setInterval,
clearInterval: window.clearInterval
},
assertInstalled: function() {
if (jasmine.Clock.installed != jasmine.Clock.defaultFakeTimer) {
throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()");
}
},
installed: null
};
jasmine.Clock.installed = jasmine.Clock.real;
window.setTimeout = function(funcToCall, millis) {
return jasmine.Clock.installed.setTimeout.apply(this, arguments);
};
window.setInterval = function(funcToCall, millis) {
return jasmine.Clock.installed.setInterval.apply(this, arguments);
};
window.clearTimeout = function(timeoutKey) {
return jasmine.Clock.installed.clearTimeout.apply(this, arguments);
};
window.clearInterval = function(timeoutKey) {
return jasmine.Clock.installed.clearInterval.apply(this, arguments);
};

74
spec/runner.html Normal file
View File

@@ -0,0 +1,74 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Test Runner</title>
</head>
<script type="text/javascript" src="lib/json2.js"></script>
<script type="text/javascript" src="../src/base.js"></script>
<script type="text/javascript" src="../src/util.js"></script>
<script type="text/javascript" src="../src/Env.js"></script>
<script type="text/javascript" src="../src/ActionCollection.js"></script>
<script type="text/javascript" src="../src/Matchers.js"></script>
<script type="text/javascript" src="../src/NestedResults.js"></script>
<script type="text/javascript" src="../src/PrettyPrinter.js"></script>
<script type="text/javascript" src="../src/QueuedFunction.js"></script>
<script type="text/javascript" src="../src/Reporters.js"></script>
<script type="text/javascript" src="../src/Runner.js"></script>
<script type="text/javascript" src="../src/Spec.js"></script>
<script type="text/javascript" src="../src/Suite.js"></script>
<script type="text/javascript" src="../lib/TrivialReporter.js"></script>
<script type="text/javascript" src="../lib/json_reporter.js"></script>
<script type="text/javascript" src="lib/mock-timeout.js"></script>
<script type="text/javascript">
jasmine.include('suites/JsonReporterTest.js', true);
jasmine.include('suites/MatchersTest.js', true);
jasmine.include('suites/NestedResultsTest.js', true);
jasmine.include('suites/PrettyPrintTest.js', true);
jasmine.include('suites/ReporterTest.js', true);
jasmine.include('suites/RunnerTest.js', true);
jasmine.include('suites/SpecRunningTest.js', true);
jasmine.include('suites/SpyTest.js', true);
</script>
<style type="text/css">
.spec {
margin: 5px;
}
.passed {
background-color: lightgreen;
}
.failed {
background-color: pink;
}
.resultMessage {
white-space: pre;
}
.stackTrace {
white-space: pre;
font-size: .8em;
margin-left: 10px;
}
</style>
<body>
<script type="text/javascript">
var jasmineEnv = jasmine.getEnv();
jasmineEnv.reporter = new jasmine.TrivialReporter();
jasmineEnv.execute();
console.log('env', jasmineEnv);
</script>
</body>
</html>

View File

@@ -0,0 +1,53 @@
describe("jasmine.Reporters.JSON", function () {
var env;
var expectedSpecJSON;
var expectedSuiteJSON;
var expectedRunnerJSON;
beforeEach(function() {
env = new jasmine.Env();
env.describe('Suite for JSON Reporter, NO DOM', function () {
env.it('should be a test', function() {
this.runs(function () {
this.expect(true).toEqual(true);
});
});
});
env.reporter = jasmine.Reporters.JSON();
var runner = env.currentRunner;
runner.execute();
expectedSpecJSON = {
"totalCount":1,"passedCount":1,"failedCount":0,"skipped":false,
"items_":[{"type": 'ExpectationResult', "passed":true,"message":"Passed.", trace: jasmine.any(Object), details: jasmine.any(Object)}],
"description":"should be a test"
};
expectedSuiteJSON = {
"totalCount":1,"passedCount":1,"failedCount":0,"skipped":false, items_:[]
};
expectedRunnerJSON = {
"totalCount":1,"passedCount":1,"failedCount":0,"skipped":false, items_:[]
};
});
it("should report spec results as json", function() {
var specJSON = env.reporter.specJSON;
expect(JSON.parse(specJSON)).toEqual(expectedSpecJSON);
});
it("should report test results as json", function() {
var suiteJSON = env.reporter.suiteJSON;
expect(JSON.parse(suiteJSON)).toEqual(expectedSuiteJSON);
});
it("should report test results as json", function() {
var runnerJSON = env.reporter.runnerJSON;
expect(JSON.parse(runnerJSON)).toEqual(expectedRunnerJSON);
});
});

301
spec/suites/MatchersTest.js Normal file
View File

@@ -0,0 +1,301 @@
describe("jasmine.Matchers", function() {
var env;
beforeEach(function() {
env = new jasmine.Env();
});
function match(value) {
return new jasmine.Matchers(env, value);
}
function detailsFor(actual, matcherName, matcherArgs) {
var matcher = match(actual);
matcher[matcherName].apply(matcher, matcherArgs);
expect(matcher.getResults().getItems().length).toEqual(1);
return matcher.getResults().getItems()[0].details;
}
it("toEqual with primitives, objects, dates, html nodes, etc.", function() {
expect(match(true).toEqual(true)).toEqual(true);
expect(match({foo:'bar'}).toEqual(null)).toEqual(false);
var functionA = function() { return 'hi'; };
var functionB = function() { return 'hi'; };
expect(match({foo:functionA}).toEqual({foo:functionB})).toEqual(false);
expect(match({foo:functionA}).toEqual({foo:functionA})).toEqual(true);
expect((match(false).toEqual(true))).toEqual(false);
var circularGraph = {};
circularGraph.referenceToSelf = circularGraph;
expect((match(circularGraph).toEqual(circularGraph))).toEqual(true);
var nodeA = document.createElement('div');
var nodeB = document.createElement('div');
expect((match(nodeA).toEqual(nodeA))).toEqual(true);
expect((match(nodeA).toEqual(nodeB))).toEqual(false);
expect((match(new Date(2008, 1, 3, 15, 17, 19, 1234)).toEqual(new Date(2009, 1, 3, 15, 17, 19, 1234)))).toEqual(false);
expect((match(new Date(2008, 1, 3, 15, 17, 19, 1234)).toEqual(new Date(2008, 1, 3, 15, 17, 19, 1234)))).toEqual(true);
expect(match(true).toNotEqual(false)).toEqual(true);
expect((match(true).toNotEqual(true))).toEqual(false);
expect((match(['a', 'b']).toEqual(['a', undefined]))).toEqual(false);
expect((match(['a', 'b']).toEqual(['a', 'b', undefined]))).toEqual(false);
});
it('toBe should return true only if the expected and actual items === each other', function() {
var a = {};
var b = {};
//noinspection UnnecessaryLocalVariableJS
var c = a;
expect((match(a).toBe(b))).toEqual(false);
expect((match(a).toBe(a))).toEqual(true);
expect((match(a).toBe(c))).toEqual(true);
expect((match(a).toNotBe(b))).toEqual(true);
expect((match(a).toNotBe(a))).toEqual(false);
expect((match(a).toNotBe(c))).toEqual(false);
});
it("toMatch and #toNotMatch should perform regular expression matching on strings", function() {
expect((match('foobarbel').toMatch(/bar/))).toEqual(true);
expect((match('foobazbel').toMatch(/bar/))).toEqual(false);
expect((match('foobarbel').toMatch("bar"))).toEqual(true);
expect((match('foobazbel').toMatch("bar"))).toEqual(false);
expect((match('foobarbel').toNotMatch(/bar/))).toEqual(false);
expect((match('foobazbel').toNotMatch(/bar/))).toEqual(true);
expect((match('foobarbel').toNotMatch("bar"))).toEqual(false);
expect((match('foobazbel').toNotMatch("bar"))).toEqual(true);
});
it("toBeDefined", function() {
expect(match('foo').toBeDefined()).toEqual(true);
expect(match(undefined).toBeDefined()).toEqual(false);
});
it("toBeNull", function() {
expect(match(null).toBeNull()).toEqual(true);
expect(match(undefined).toBeNull()).toEqual(false);
expect(match("foo").toBeNull()).toEqual(false);
});
it("toBeFalsy", function() {
expect(match(false).toBeFalsy()).toEqual(true);
expect(match(true).toBeFalsy()).toEqual(false);
expect(match(undefined).toBeFalsy()).toEqual(true);
expect(match(0).toBeFalsy()).toEqual(true);
expect(match("").toBeFalsy()).toEqual(true);
});
it("toBeTruthy", function() {
expect(match(false).toBeTruthy()).toEqual(false);
expect(match(true).toBeTruthy()).toEqual(true);
expect(match(undefined).toBeTruthy()).toEqual(false);
expect(match(0).toBeTruthy()).toEqual(false);
expect(match("").toBeTruthy()).toEqual(false);
expect(match("hi").toBeTruthy()).toEqual(true);
expect(match(5).toBeTruthy()).toEqual(true);
expect(match({foo: 1}).toBeTruthy()).toEqual(true);
});
it("toEqual", function() {
expect(match(undefined).toEqual(undefined)).toEqual(true);
expect(match({foo:'bar'}).toEqual({foo:'bar'})).toEqual(true);
expect(match("foo").toEqual({bar: undefined})).toEqual(false);
expect(match({foo: undefined}).toEqual("goo")).toEqual(false);
expect(match({foo: {bar :undefined}}).toEqual("goo")).toEqual(false);
});
it("toEqual with jasmine.any()", function() {
expect(match("foo").toEqual(jasmine.any(String))).toEqual(true);
expect(match(3).toEqual(jasmine.any(Number))).toEqual(true);
expect(match("foo").toEqual(jasmine.any(Function))).toEqual(false);
expect(match("foo").toEqual(jasmine.any(Object))).toEqual(false);
expect(match({someObj:'foo'}).toEqual(jasmine.any(Object))).toEqual(true);
expect(match({someObj:'foo'}).toEqual(jasmine.any(Function))).toEqual(false);
expect(match(function() {}).toEqual(jasmine.any(Object))).toEqual(false);
expect(match(["foo", "goo"]).toEqual(["foo", jasmine.any(String)])).toEqual(true);
expect(match(function() {}).toEqual(jasmine.any(Function))).toEqual(true);
expect(match(["a", function() {}]).toEqual(["a", jasmine.any(Function)])).toEqual(true);
});
it("toEqual handles circular objects ok", function() {
expect(match({foo: "bar", baz: undefined}).toEqual({foo: "bar", baz: undefined})).toEqual(true);
expect(match({foo:['bar','baz','quux']}).toEqual({foo:['bar','baz','quux']})).toEqual(true);
expect(match({foo: {bar:'baz'}, quux:'corge'}).toEqual({foo:{bar:'baz'}, quux:'corge'})).toEqual(true);
var circularObject = {};
var secondCircularObject = {};
circularObject.field = circularObject;
secondCircularObject.field = secondCircularObject;
expect(match(circularObject).toEqual(secondCircularObject)).toEqual(true);
});
it("toNotEqual as slightly surprising behavior, but is it intentional?", function() {
expect(match({x:"x", y:"y", z:"w"}).toNotEqual({x:"x", y:"y", z:"z"})).toEqual(true);
expect(match({x:"x", y:"y", w:"z"}).toNotEqual({x:"x", y:"y", z:"z"})).toEqual(true);
expect(match({x:"x", y:"y", z:"z"}).toNotEqual({w: "w", x:"x", y:"y", z:"z"})).toEqual(true);
expect(match({w: "w", x:"x", y:"y", z:"z"}).toNotEqual({x:"x", y:"y", z:"z"})).toEqual(true);
});
it("toEqual handles arrays", function() {
expect(match([1, "A"]).toEqual([1, "A"])).toEqual(true);
});
it("toContain and toNotContain", function() {
expect(match('ABC').toContain('A')).toEqual(true);
expect(match('ABC').toContain('X')).toEqual(false);
expect(match(['A', 'B', 'C']).toContain('A')).toEqual(true);
expect(match(['A', 'B', 'C']).toContain('F')).toEqual(false);
expect(match(['A', 'B', 'C']).toNotContain('F')).toEqual(true);
expect(match(['A', 'B', 'C']).toNotContain('A')).toEqual(false);
expect(match(['A', {some:'object'}, 'C']).toContain({some:'object'})).toEqual(true);
expect(match(['A', {some:'object'}, 'C']).toContain({some:'other object'})).toEqual(false);
expect(detailsFor('abc', 'toContain', ['x'])).toEqual({
matcherName: 'toContain', expected: 'x', actual: 'abc'
});
});
it("toThrow", function() {
var expected = new jasmine.Matchers(env, function() {
throw new Error("Fake Error");
});
expect(expected.toThrow()).toEqual(true);
expect(expected.toThrow("Fake Error")).toEqual(true);
expect(expected.toThrow(new Error("Fake Error"))).toEqual(true);
expect(expected.toThrow("Other Error")).toEqual(false);
expect(expected.toThrow(new Error("Other Error"))).toEqual(false);
expect(match(function() {}).toThrow()).toEqual(false);
});
it("wasCalled, wasNotCalled, wasCalledWith", function() {
var currentSuite;
var spec;
currentSuite = env.describe('default current suite', function() {
spec = env.it();
});
var TestClass = { someFunction: function() {
} };
var expected;
expect(match(TestClass.someFunction).wasCalled()).toEqual(false);
expect(match(TestClass.someFunction).wasNotCalled()).toEqual(false);
spec.spyOn(TestClass, 'someFunction');
expect(match(TestClass.someFunction).wasCalled()).toEqual(false);
expect(match(TestClass.someFunction).wasNotCalled()).toEqual(true);
TestClass.someFunction();
expect(match(TestClass.someFunction).wasCalled()).toEqual(true);
expect(match(TestClass.someFunction).wasCalled('some arg')).toEqual(false);
expect(match(TestClass.someFunction).wasNotCalled()).toEqual(false);
TestClass.someFunction('a', 'b', 'c');
expect(match(TestClass.someFunction).wasCalledWith('a', 'b', 'c')).toEqual(true);
expected = match(TestClass.someFunction);
expect(expected.wasCalledWith('c', 'b', 'a')).toEqual(false);
expect(expected.getResults().getItems()[0].passed).toEqual(false);
TestClass.someFunction.reset();
TestClass.someFunction('a', 'b', 'c');
TestClass.someFunction('d', 'e', 'f');
expect(expected.wasCalledWith('a', 'b', 'c')).toEqual(true);
expect(expected.wasCalledWith('d', 'e', 'f')).toEqual(true);
expect(expected.wasCalledWith('x', 'y', 'z')).toEqual(false);
expect(detailsFor(TestClass.someFunction, 'wasCalledWith', ['x', 'y', 'z'])).toEqual({
matcherName: 'wasCalledWith', expected: ['x', 'y', 'z'], actual: TestClass.someFunction.argsForCall
});
});
it("should report mismatches in some nice way", function() {
var results = new jasmine.NestedResults();
var expected = new jasmine.Matchers(env, true, results);
expected.toEqual(true);
expected.toEqual(false);
expect(results.getItems().length).toEqual(2);
expect(results.getItems()[0].passed).toEqual(true);
expect(results.getItems()[1].passed).toEqual(false);
results = new jasmine.NestedResults();
expected = new jasmine.Matchers(env, false, results);
expected.toEqual(true);
var expectedMessage = 'Expected<br /><br />true<br /><br />but got<br /><br />false<br />';
expect(results.getItems()[0].message).toEqual(expectedMessage);
results = new jasmine.NestedResults();
expected = new jasmine.Matchers(env, null, results);
expected.toEqual('not null');
expectedMessage = 'Expected<br /><br />\'not null\'<br /><br />but got<br /><br />null<br />';
expect(results.getItems()[0].message).toEqual(expectedMessage);
results = new jasmine.NestedResults();
expected = new jasmine.Matchers(env, undefined, results);
expected.toEqual('not undefined');
expectedMessage = 'Expected<br /><br />\'not undefined\'<br /><br />but got<br /><br />undefined<br />';
expect(results.getItems()[0].message).toEqual(expectedMessage);
results = new jasmine.NestedResults();
expected = new jasmine.Matchers(env, {foo:'one',baz:'two', more: 'blah'}, results);
expected.toEqual({foo:'one', bar: '<b>three</b> &', baz: '2'});
expectedMessage =
"Expected<br /><br />{ foo : 'one', bar : '&lt;b&gt;three&lt;/b&gt; &amp;', baz : '2' }<br /><br />but got<br /><br />{ foo : 'one', baz : 'two', more : 'blah' }<br />" +
"<br /><br />Different Keys:<br />" +
"expected has key 'bar', but missing from <b>actual</b>.<br />" +
"<b>expected</b> missing key 'more', but present in actual.<br />" +
"<br /><br />Different Values:<br />" +
"'bar' was<br /><br />'&lt;b&gt;three&lt;/b&gt; &amp;'<br /><br />in expected, but was<br /><br />'undefined'<br /><br />in actual.<br /><br />" +
"'baz' was<br /><br />'2'<br /><br />in expected, but was<br /><br />'two'<br /><br />in actual.<br /><br />";
var actualMessage = results.getItems()[0].message;
expect(actualMessage).toEqual(expectedMessage);
results = new jasmine.NestedResults();
expected = new jasmine.Matchers(env, true, results);
expected.toEqual(true);
expect(results.getItems()[0].message).toEqual('Passed.');
expected = new jasmine.Matchers(env, [1, 2, 3], results);
results.getItems().length = 0;
expected.toEqual([1, 2, 3]);
expect(results.getItems()[0].passed).toEqual(true);
expected = new jasmine.Matchers(env, [1, 2, 3], results);
results.getItems().length = 0;
expected.toEqual([{}, {}, {}]);
expect(results.getItems()[0].passed).toEqual(false);
expected = new jasmine.Matchers(env, [{}, {}, {}], results);
results.getItems().length = 0;
expected.toEqual([1, 2, 3]);
expect(results.getItems()[0].passed).toEqual(false);
});
});

View File

@@ -0,0 +1,41 @@
describe('jasmine.NestedResults', function() {
it('#addResult increments counters', function() {
// Leaf case
var results = new jasmine.NestedResults();
results.addResult({passed: true, message: 'Passed.'});
expect(results.getItems().length).toEqual(1);
expect(results.totalCount).toEqual(1);
expect(results.passedCount).toEqual(1);
expect(results.failedCount).toEqual(0);
results.addResult({passed: false, message: 'FAIL.'});
expect(results.getItems().length).toEqual(2);
expect(results.totalCount).toEqual(2);
expect(results.passedCount).toEqual(1);
expect(results.failedCount).toEqual(1);
});
it('should roll up counts for nested results', function() {
// Branch case
var leafResultsOne = new jasmine.NestedResults();
leafResultsOne.addResult({passed: true, message: ''});
leafResultsOne.addResult({passed: false, message: ''});
var leafResultsTwo = new jasmine.NestedResults();
leafResultsTwo.addResult({passed: true, message: ''});
leafResultsTwo.addResult({passed: false, message: ''});
var branchResults = new jasmine.NestedResults();
branchResults.addResult(leafResultsOne);
branchResults.addResult(leafResultsTwo);
expect(branchResults.getItems().length).toEqual(2);
expect(branchResults.totalCount).toEqual(4);
expect(branchResults.passedCount).toEqual(2);
expect(branchResults.failedCount).toEqual(2);
});
});

View File

@@ -0,0 +1,62 @@
describe("jasmine.pp", function () {
it("should wrap strings in single quotes", function() {
expect(jasmine.pp("some string")).toEqual("'some string'");
expect(jasmine.pp("som' string")).toEqual("'som' string'");
});
it("should stringify primitives properly", function() {
expect(jasmine.pp(true)).toEqual("true");
expect(jasmine.pp(false)).toEqual("false");
expect(jasmine.pp(null)).toEqual("null");
expect(jasmine.pp(undefined)).toEqual("undefined");
expect(jasmine.pp(3)).toEqual("3");
expect(jasmine.pp(-3.14)).toEqual("-3.14");
});
it("should stringify arrays properly", function() {
expect(jasmine.pp([1, 2])).toEqual("[ 1, 2 ]");
expect(jasmine.pp([1, 'foo', {}, undefined, null])).toEqual("[ 1, 'foo', { }, undefined, null ]");
});
it("should indicate circular array references", function() {
var array1 = [1, 2];
var array2 = [array1];
array1.push(array2);
expect(jasmine.pp(array1)).toEqual("[ 1, 2, [ <circular reference: Array> ] ]");
});
it("should stringify objects properly", function() {
expect(jasmine.pp({foo: 'bar'})).toEqual("{ foo : 'bar' }");
expect(jasmine.pp({foo:'bar', baz:3, nullValue: null, undefinedValue: undefined})).toEqual("{ foo : 'bar', baz : 3, nullValue : null, undefinedValue : undefined }");
expect(jasmine.pp({foo: function () { }, bar: [1, 2, 3]})).toEqual("{ foo : Function, bar : [ 1, 2, 3 ] }");
});
it("should indicate circular object references", function() {
var sampleValue = {foo: 'hello'};
sampleValue.nested = sampleValue;
expect(jasmine.pp(sampleValue)).toEqual("{ foo : 'hello', nested : <circular reference: Object> }");
});
it("should indicate getters on objects as such", function() {
var sampleValue = {id: 1};
sampleValue.__defineGetter__('calculatedValue', function() { throw new Error("don't call me!"); });
expect(jasmine.pp(sampleValue)).toEqual("{ id : 1, calculatedValue : <getter> }");
});
it("should stringify HTML nodes properly", function() {
var sampleNode = document.createElement('div');
sampleNode.innerHTML = 'foo<b>bar</b>';
expect(jasmine.pp(sampleNode)).toEqual("HTMLNode");
expect(jasmine.pp({foo: sampleNode})).toEqual("{ foo : HTMLNode }");
});
it('should not do HTML escaping of strings', function() {
expect(jasmine.pp('some <b>html string</b> &', false)).toEqual('\'some <b>html string</b> &\'');
});
it("should abbreviate window objects", function() {
expect(jasmine.pp(window)).toEqual("<window>");
});
});

View File

@@ -0,0 +1,58 @@
describe('jasmine.Reporter', function() {
var env;
beforeEach(function() {
env = new jasmine.Env();
});
it('should ', function() {
env.describe('Suite for JSON Reporter with Callbacks', function () {
env.it('should be a test', function() {
this.runs(function () {
this.expect(true).toEqual(true);
});
});
env.it('should be a failing test', function() {
this.runs(function () {
this.expect(false).toEqual(true);
});
});
});
env.describe('Suite for JSON Reporter with Callbacks 2', function () {
env.it('should be a test', function() {
this.runs(function () {
this.expect(true).toEqual(true);
});
});
});
var foo = 0;
var bar = 0;
var baz = 0;
var specCallback = function (results) {
foo++;
};
var suiteCallback = function (results) {
bar++;
};
var runnerCallback = function (results) {
baz++;
};
env.reporter = jasmine.Reporters.reporter({
specCallback: specCallback,
suiteCallback: suiteCallback,
runnerCallback: runnerCallback
});
var runner = env.currentRunner;
runner.execute();
expect(foo).toEqual(3); // 'foo was expected to be 3, was ' + foo);
expect(bar).toEqual(2); // 'bar was expected to be 2, was ' + bar);
expect(baz).toEqual(1); // 'baz was expected to be 1, was ' + baz);
});
});

98
spec/suites/RunnerTest.js Normal file
View File

@@ -0,0 +1,98 @@
describe('RunnerTest', function() {
var env;
beforeEach(function () {
env = new jasmine.Env();
});
it('should be able to add a suite', function() {
env.describe('one suite description', function () {
env.it('should be a test');
});
expect(env.currentRunner.suites.length).toEqual(1); // "Runner expected one suite, got " + env.currentRunner.suites.length);
});
it('should be able to push multiple suites', function() {
env.describe('one suite description', function () {
env.it('should be a test');
});
env.describe('another suite description', function () {
env.it('should be a test');
});
expect(env.currentRunner.suites.length).toEqual(2); //"Runner expected two suites, but got " + env.currentRunner.suites.length);
});
it('should run child suites and specs and generate results when execute is called', function() {
env.describe('one suite description', function () {
env.it('should be a test', function() {
this.runs(function () {
this.expect(true).toEqual(true);
});
});
});
env.describe('another suite description', function () {
env.it('should be another test', function() {
this.runs(function () {
this.expect(true).toEqual(false);
});
});
});
env.currentRunner.execute();
expect(env.currentRunner.suites.length).toEqual(2); // "Runner expected two suites, got " + env.currentRunner.suites.length);
expect(env.currentRunner.suites[0].specs[0].results.getItems()[0].passed).toEqual(true); //"Runner should have run specs in first suite");
expect(env.currentRunner.suites[1].specs[0].results.getItems()[0].passed).toEqual(false); //"Runner should have run specs in second suite");
});
it('should ignore suites that have been x\'d', function() {
env.xdescribe('one suite description', function () {
env.it('should be a test', function() {
this.runs(function () {
this.expect(true).toEqual(true);
});
});
});
env.describe('another suite description', function () {
env.it('should be another test', function() {
this.runs(function () {
this.expect(true).toEqual(false);
});
});
});
env.currentRunner.execute();
expect(env.currentRunner.suites.length).toEqual(1); // "Runner expected 1 suite, got " + env.currentRunner.suites.length);
expect(env.currentRunner.suites[0].specs[0].results.getItems()[0].passed).toEqual(false); // "Runner should have run specs in first suite");
expect(env.currentRunner.suites[1]).toEqual(undefined); // "Second suite should be undefined, but was " + reporter.toJSON(env.currentRunner.suites[1]));
});
it('should roll up results from all specs', function() {
var env = new jasmine.Env();
env.describe('one suite description', function () {
env.it('should be a test', function() {
this.runs(function () {
this.expect(true).toEqual(true);
});
});
});
env.describe('another suite description', function () {
env.it('should be another test', function() {
this.runs(function () {
this.expect(true).toEqual(false);
});
});
});
env.currentRunner.execute();
var results = env.currentRunner.getResults();
expect(results.totalCount).toEqual(2);
expect(results.passedCount).toEqual(1);
expect(results.failedCount).toEqual(1);
});
});

View File

@@ -0,0 +1,730 @@
describe("jasmine spec running", function () {
var env;
var fakeTimer;
beforeEach(function() {
env = new jasmine.Env();
fakeTimer = new jasmine.FakeTimer();
env.setTimeout = fakeTimer.setTimeout;
env.clearTimeout = fakeTimer.clearTimeout;
env.setInterval = fakeTimer.setInterval;
env.clearInterval = fakeTimer.clearInterval;
});
it('should assign spec ids sequentially', function() {
var it0, it1, it2, it3, it4;
env.describe('test suite', function() {
it0 = env.it('spec 0', function() {
});
it1 = env.it('spec 1', function() {
});
it2 = env.xit('spec 2', function() {
});
it3 = env.it('spec 3', function() {
});
});
env.describe('test suite 2', function() {
it4 = env.it('spec 4', function() {
});
});
expect(it0.id).toEqual(0);
expect(it1.id).toEqual(1);
expect(it2.id).toEqual(2);
expect(it3.id).toEqual(3);
expect(it4.id).toEqual(4);
});
it("should build up some objects with results we can inspect", function() {
var specWithNoBody, specWithExpectation, specWithFailingExpectations, specWithMultipleExpectations;
var suite = env.describe('default current suite', function() {
specWithNoBody = env.it('new spec');
specWithExpectation = env.it('spec with an expectation').runs(function () {
var foo = 'bar';
this.expect(foo).toEqual('bar');
});
specWithFailingExpectations = env.it('spec with failing expectation').runs(function () {
var foo = 'bar';
this.expect(foo).toEqual('baz');
});
specWithMultipleExpectations = env.it('spec with multiple assertions').runs(function () {
var foo = 'bar';
var baz = 'quux';
this.expect(foo).toEqual('bar');
this.expect(baz).toEqual('quux');
});
});
suite.execute();
expect(specWithNoBody.description).toEqual('new spec');
expect(specWithExpectation.results.getItems().length).toEqual(1); // "Results aren't there after a spec was executed"
expect(specWithExpectation.results.getItems()[0].passed).toEqual(true); // "Results has a result, but it's true"
expect(specWithExpectation.results.description).toEqual('spec with an expectation'); // "Spec's results did not get the spec's description"
expect(specWithFailingExpectations.results.getItems()[0].passed).toEqual(false); // "Expectation that failed, passed"
expect(specWithMultipleExpectations.results.getItems().length).toEqual(2); // "Spec doesn't support multiple expectations"
});
it("should work without a runs block", function() {
var another_spec;
var currentSuite = env.describe('default current suite', function() {
another_spec = env.it('spec with an expectation', function () {
var foo = 'bar';
this.expect(foo).toEqual('bar');
this.expect(foo).toEqual('baz');
});
});
another_spec.execute();
another_spec.done = true;
expect(another_spec.results.getItems().length).toEqual(2);
expect(another_spec.results.getItems()[0].passed).toEqual(true); // "In a spec without a run block, expected first expectation result to be true but was false"
expect(another_spec.results.getItems()[1].passed).toEqual(false); // "In a spec without a run block, expected second expectation result to be false but was true";
expect(another_spec.results.description).toEqual('spec with an expectation'); // "In a spec without a run block, results did not include the spec's description";
});
it("should run asynchronous tests", function () {
var foo = 0;
//set a bogus suite for the spec to attach to
// jasmine.getEnv().currentSuite = {specs: []};
var a_spec;
env.describe('test async spec', function() {
a_spec = env.it('simple queue test', function () {
this.runs(function () {
foo++;
});
this.runs(function () {
this.expect(foo).toEqual(1);
});
});
});
expect(a_spec.queue.length).toEqual(1,
'Expected spec queue length to be 1, was ' + a_spec.queue.length);
a_spec.execute();
expect(a_spec.queue.length).toEqual(3,
'Expected spec queue length to be 3, was ' + a_spec.queue.length);
foo = 0;
env.describe('test async spec', function() {
a_spec = env.it('spec w/ queued statments', function () {
this.runs(function () {
foo++;
});
this.runs(function () {
this.expect(foo).toEqual(1);
});
});
});
a_spec.execute();
expect(a_spec.results.getItems().length).toEqual(1); // 'No call to waits(): Spec queue did not run all functions';
expect(a_spec.results.getItems()[0].passed).toEqual(true); // 'No call to waits(): Queued expectation failed';
foo = 0;
env.describe('test async spec', function() {
a_spec = env.it('spec w/ queued statments', function () {
this.runs(function () {
fakeTimer.setTimeout(function() {
foo++;
}, 500);
});
this.waits(1000);
this.runs(function() {
this.expect(foo).toEqual(1);
});
});
});
a_spec.execute();
expect(a_spec.results.getItems().length).toEqual(0);
fakeTimer.tick(500);
expect(a_spec.results.getItems().length).toEqual(0);
fakeTimer.tick(500);
expect(a_spec.results.getItems().length).toEqual(1); // 'Calling waits(): Spec queue did not run all functions';
expect(a_spec.results.getItems()[0].passed).toEqual(true); // 'Calling waits(): Queued expectation failed';
var bar = 0;
var another_spec;
env.describe('test async spec', function() {
another_spec = env.it('spec w/ queued statments', function () {
this.runs(function () {
fakeTimer.setTimeout(function() {
bar++;
}, 250);
});
this.waits(500);
this.runs(function () {
fakeTimer.setTimeout(function() {
bar++;
}, 250);
});
this.waits(500);
this.runs(function () {
this.expect(bar).toEqual(2);
});
});
});
expect(another_spec.queue.length).toEqual(1); // 'Calling 2 waits(): Expected queue length to be 1, got ' + another_spec.queue.length;
another_spec.execute();
fakeTimer.tick(1000);
expect(another_spec.queue.length).toEqual(4); // 'Calling 2 waits(): Expected queue length to be 4, got ' + another_spec.queue.length;
expect(another_spec.results.getItems().length).toEqual(1); // 'Calling 2 waits(): Spec queue did not run all functions';
expect(another_spec.results.getItems()[0].passed).toEqual(true); // 'Calling 2 waits(): Queued expectation failed';
var baz = 0;
var yet_another_spec;
env.describe('test async spec', function() {
yet_another_spec = env.it('spec w/ async fail', function () {
this.runs(function () {
fakeTimer.setTimeout(function() {
baz++;
}, 250);
});
this.waits(100);
this.runs(function() {
this.expect(baz).toEqual(1);
});
});
});
yet_another_spec.execute();
fakeTimer.tick(250);
expect(yet_another_spec.queue.length).toEqual(3); // 'Calling 2 waits(): Expected queue length to be 3, got ' + another_spec.queue.length);
expect(yet_another_spec.results.getItems().length).toEqual(1); // 'Calling 2 waits(): Spec queue did not run all functions');
expect(yet_another_spec.results.getItems()[0].passed).toEqual(false); // 'Calling 2 waits(): Queued expectation failed');
});
it("testAsyncSpecsWithMockSuite", function () {
var bar = 0;
var another_spec;
env.describe('test async spec', function() {
another_spec = env.it('spec w/ queued statments', function () {
this.runs(function () {
fakeTimer.setTimeout(function() {
bar++;
}, 250);
});
this.waits(500);
this.runs(function () {
fakeTimer.setTimeout(function() {
bar++;
}, 250);
});
this.waits(1500);
this.runs(function() {
this.expect(bar).toEqual(2);
});
});
});
another_spec.execute();
fakeTimer.tick(2000);
expect(another_spec.queue.length).toEqual(4); // 'Calling 2 waits(): Expected queue length to be 4, got ' + another_spec.queue.length);
expect(another_spec.results.getItems().length).toEqual(1); // 'Calling 2 waits(): Spec queue did not run all functions');
expect(another_spec.results.getItems()[0].passed).toEqual(true); // 'Calling 2 waits(): Queued expectation failed');
});
it("testWaitsFor", function() {
var doneWaiting = false;
var runsBlockExecuted = false;
var spec;
env.describe('foo', function() {
spec = env.it('has a waits for', function() {
this.runs(function() {
});
this.waitsFor(500, function() {
return doneWaiting;
});
this.runs(function() {
runsBlockExecuted = true;
});
});
});
spec.execute();
expect(runsBlockExecuted).toEqual(false); //, 'should not have executed runs block yet');
fakeTimer.tick(100);
doneWaiting = true;
fakeTimer.tick(100);
expect(runsBlockExecuted).toEqual(true); //, 'should have executed runs block');
});
it("testWaitsForFailsWithMessage", function() {
var spec;
env.describe('foo', function() {
spec = env.it('has a waits for', function() {
this.runs(function() {
});
this.waitsFor(500, function() {
return false; // force a timeout
}, 'my awesome condition');
this.runs(function() {
});
});
});
spec.execute();
fakeTimer.tick(1000);
var actual = spec.results.getItems()[0].message;
var expected = 'timeout: timed out after 500 msec waiting for my awesome condition';
expect(actual).toEqual(expected);
});
it("testWaitsForFailsIfTimeout", function() {
var runsBlockExecuted = false;
var spec;
env.describe('foo', function() {
spec = env.it('has a waits for', function() {
this.runs(function() {
});
this.waitsFor(500, function() {
return false; // force a timeout
});
this.runs(function() {
runsBlockExecuted = true;
});
});
});
spec.execute();
expect(runsBlockExecuted).toEqual(false, 'should not have executed runs block yet');
fakeTimer.tick(100);
expect(runsBlockExecuted).toEqual(false, 'should not have executed runs block yet');
fakeTimer.tick(400);
expect(runsBlockExecuted).toEqual(false, 'should have timed out, so the second runs block should not have been called');
var actual = spec.results.getItems()[0].message;
var expected = 'timeout: timed out after 500 msec waiting for something to happen';
expect(actual).toEqual(expected,
'expected "' + expected + '" but found "' + actual + '"');
});
it("testSpecAfter", function() {
var log = "";
var spec;
var suite = env.describe("has after", function() {
spec = env.it('spec with after', function() {
this.runs(function() {
log += "spec";
});
});
});
spec.after(function() {
log += "after1";
});
spec.after(function() {
log += "after2";
});
suite.execute();
expect(log).toEqual("specafter2after1"); // "after function should be executed in reverse order after spec runs");
});
describe('test suite declaration', function() {
var suite;
var dummyFunction = function() {};
it('should give the suite a description', function() {
suite = env.describe('one suite description', dummyFunction);
expect(suite.description).toEqual('one suite description'); // 'Suite did not get a description');
});
it('should add tests to suites declared by the passed function', function() {
suite = env.describe('one suite description', function () {
env.it('should be a test');
});
expect(suite.specs.length).toEqual(1); // 'Suite did not get a spec pushed');
expect(suite.specs[0].queue.length).toEqual(0); // "Suite's Spec should not have queuedFunctions");
});
it('should enqueue functions for multipart tests', function() {
suite = env.describe('one suite description', function () {
env.it('should be a test with queuedFunctions', function() {
this.runs(function() {
var foo = 0;
foo++;
});
});
});
expect(suite.specs[0].queue.length).toEqual(1); // "Suite's spec did not get a function pushed");
});
it('should enqueue functions for multipart tests and support waits, and run any ready runs() blocks', function() {
var foo = 0;
var bar = 0;
suite = env.describe('one suite description', function () {
env.it('should be a test with queuedFunctions', function() {
this.runs(function() {
foo++;
});
this.waits(100);
this.runs(function() {
bar++;
});
});
});
expect(suite.specs[0].queue.length).toEqual(1); // "Suite's spec length should have been 1, was " + suite.specs[0].queue.length);
suite.execute();
expect(suite.specs[0].queue.length).toEqual(3); // "Suite's spec length should have been 3, was " + suite.specs[0].queue.length);
expect(foo).toEqual(1);
expect(bar).toEqual(0);
fakeTimer.tick(100);
expect(bar).toEqual(1);
});
});
it("testBeforeAndAfterCallbacks", function () {
var suiteWithBefore = env.describe('one suite with a before', function () {
this.beforeEach(function () {
this.foo = 1;
});
env.it('should be a spec', function () {
this.runs(function() {
this.foo++;
this.expect(this.foo).toEqual(2);
});
});
env.it('should be another spec', function () {
this.runs(function() {
this.foo++;
this.expect(this.foo).toEqual(2);
});
});
});
suiteWithBefore.execute();
var suite = suiteWithBefore;
expect(suite.beforeEachFunction); // "testBeforeAndAfterCallbacks: Suite's beforeEach was not defined");
expect(suite.specs[0].results.getItems()[0].passed).toEqual(true); // "testBeforeAndAfterCallbacks: the first spec's foo should have been 2");
expect(suite.specs[1].results.getItems()[0].passed).toEqual(true); // "testBeforeAndAfterCallbacks: the second spec's this.foo should have been 2");
var suiteWithAfter = env.describe('one suite with an after_each', function () {
env.it('should be a spec with an after_each', function () {
this.runs(function() {
this.foo = 0;
this.foo++;
this.expect(this.foo).toEqual(1);
});
});
env.it('should be another spec with an after_each', function () {
this.runs(function() {
this.foo = 0;
this.foo++;
this.expect(this.foo).toEqual(1);
});
});
this.afterEach(function () {
this.foo = 0;
});
});
suiteWithAfter.execute();
var suite = suiteWithAfter;
expect(suite.afterEachFunction); // "testBeforeAndAfterCallbacks: Suite's afterEach was not defined");
expect(suite.specs[0].results.getItems()[0].passed).toEqual(true); // "testBeforeAndAfterCallbacks: afterEach failure: " + suite.results.getItems()[0].results[0].message);
expect(suite.specs[0].foo).toEqual(0); // "testBeforeAndAfterCallbacks: afterEach failure: foo was not reset to 0");
expect(suite.specs[1].results.getItems()[0].passed).toEqual(true); // "testBeforeAndAfterCallbacks: afterEach failure: " + suite.results.getItems()[0].results[0].message);
expect(suite.specs[1].foo).toEqual(0); // "testBeforeAndAfterCallbacks: afterEach failure: foo was not reset to 0");
});
it("testBeforeExecutesSafely", function() {
var report = "";
var suite = env.describe('before fails on first test, passes on second', function() {
var counter = 0;
this.beforeEach(function() {
counter++;
if (counter == 1) {
throw "before failure";
}
});
env.it("first should not run because before fails", function() {
this.runs(function() {
report += "first";
this.expect(true).toEqual(true);
});
});
env.it("second should run and pass because before passes", function() {
this.runs(function() {
report += "second";
this.expect(true).toEqual(true);
});
});
});
suite.execute();
expect(report).toEqual("firstsecond"); // "both tests should run");
expect(suite.specs[0].results.getItems()[0].passed).toEqual(false); // "1st spec should fail");
expect(suite.specs[1].results.getItems()[0].passed).toEqual(true); // "2nd spec should pass");
expect(suite.specs[0].results.getItems()[0].passed).toEqual(false); // "1st spec should fail");
expect(suite.specs[1].results.getItems()[0].passed).toEqual(true); // "2nd spec should pass");
});
it("testAfterExecutesSafely", function() {
var report = "";
var suite = env.describe('after fails on first test, then passes', function() {
var counter = 0;
this.afterEach(function() {
counter++;
if (counter == 1) {
throw "after failure";
}
});
env.it("first should run, expectation passes, but spec fails because after fails", function() {
this.runs(function() {
report += "first";
this.expect(true).toEqual(true);
});
});
env.it("second should run and pass because after passes", function() {
this.runs(function() {
report += "second";
this.expect(true).toEqual(true);
});
});
env.it("third should run and pass because after passes", function() {
this.runs(function() {
report += "third";
this.expect(true).toEqual(true);
});
});
});
suite.execute();
expect(report).toEqual("firstsecondthird"); // "all tests should run");
//After each errors should not go in spec results because it confuses the count.
expect(suite.specs.length).toEqual(3, 'testAfterExecutesSafely should have results for three specs');
expect(suite.specs[0].results.getItems()[0].passed).toEqual(true, "testAfterExecutesSafely 1st spec should pass");
expect(suite.specs[1].results.getItems()[0].passed).toEqual(true, "testAfterExecutesSafely 2nd spec should pass");
expect(suite.specs[2].results.getItems()[0].passed).toEqual(true, "testAfterExecutesSafely 3rd spec should pass");
expect(suite.specs[0].results.getItems()[0].passed).toEqual(true, "testAfterExecutesSafely 1st result for 1st suite spec should pass");
expect(suite.specs[0].results.getItems()[1].passed).toEqual(false, "testAfterExecutesSafely 2nd result for 1st suite spec should fail because afterEach failed");
expect(suite.specs[1].results.getItems()[0].passed).toEqual(true, "testAfterExecutesSafely 2nd suite spec should pass");
expect(suite.specs[2].results.getItems()[0].passed).toEqual(true, "testAfterExecutesSafely 3rd suite spec should pass");
});
it("testNestedDescribes", function() {
var actions = [];
env.describe('Something', function() {
env.beforeEach(function() {
actions.push('outer beforeEach');
});
env.afterEach(function() {
actions.push('outer afterEach');
});
env.it('does it 1', function() {
actions.push('outer it 1');
});
env.describe('Inner 1', function() {
env.beforeEach(function() {
actions.push('inner 1 beforeEach');
});
env.afterEach(function() {
actions.push('inner 1 afterEach');
});
env.it('does it 2', function() {
actions.push('inner 1 it');
});
});
env.it('does it 3', function() {
actions.push('outer it 2');
});
env.describe('Inner 2', function() {
env.beforeEach(function() {
actions.push('inner 2 beforeEach');
});
env.afterEach(function() {
actions.push('inner 2 afterEach');
});
env.it('does it 2', function() {
actions.push('inner 2 it');
});
});
});
env.execute();
var expected = [
"outer beforeEach",
"outer it 1",
"outer afterEach",
"outer beforeEach",
"inner 1 beforeEach",
"inner 1 it",
"inner 1 afterEach",
"outer afterEach",
"outer beforeEach",
"outer it 2",
"outer afterEach",
"outer beforeEach",
"inner 2 beforeEach",
"inner 2 it",
"inner 2 afterEach",
"outer afterEach"
];
expect(env.equals_(actions, expected)).toEqual(true); // "nested describes order failed: <blockquote>" + jasmine.pp(actions) + "</blockquote> wanted <blockquote>" + jasmine.pp(expected) + "</blockquote");
});
it("builds up nested names", function() {
var nestedSpec;
env.describe('Test Subject', function() {
env.describe('when under circumstance A', function() {
env.describe('and circumstance B', function() {
nestedSpec = env.it('behaves thusly', function() {});
});
});
});
expect(nestedSpec.getFullName()).toEqual('Test Subject when under circumstance A and circumstance B behaves thusly.'); //, "Spec.fullName was incorrect: " + nestedSpec.getFullName());
});
it("should bind 'this' to the running spec within the spec body", function() {
var suite = env.describe('one suite description', function () {
env.it('should be a test with queuedFunctions', function() {
this.runs(function() {
this.foo = 0;
this.foo++;
});
this.runs(function() {
var that = this;
fakeTimer.setTimeout(function() {
that.foo++;
}, 250);
});
this.runs(function() {
this.expect(this.foo).toEqual(2);
});
this.waits(300);
this.runs(function() {
this.expect(this.foo).toEqual(2);
});
});
});
suite.execute();
fakeTimer.tick(600);
expect(suite.specs[0].foo).toEqual(2); // "Spec does not maintain scope in between functions");
expect(suite.specs[0].results.getItems().length).toEqual(2); // "Spec did not get results for all expectations");
expect(suite.specs[0].results.getItems()[0].passed).toEqual(false); // "Spec did not return false for a failed expectation");
expect(suite.specs[0].results.getItems()[1].passed).toEqual(true); // "Spec did not return true for a passing expectation");
});
it("shouldn't run disabled tests", function() {
var xitSpecWasRun = false;
var suite = env.describe('default current suite', function() {
env.xit('disabled spec').runs(function () {
xitSpecWasRun = true;
});
env.it('enabled spec').runs(function () {
var foo = 'bar';
expect(foo).toEqual('bar');
});
});
suite.execute();
expect(suite.specs.length).toEqual(1);
expect(xitSpecWasRun).toEqual(false);
});
it('shouldn\'t execute specs in disabled suites', function() {
var spy = jasmine.createSpy();
var disabledSuite = env.xdescribe('a disabled suite', function() {
it('enabled spec, but should not be run', function() {
spy();
});
});
disabledSuite.execute();
expect(spy).wasNotCalled();
});
it('#explodes should throw an exception when it is called inside a spec', function() {
var exceptionMessage = false;
var suite = env.describe('Spec', function () {
it('plodes', function() {
try {
jasmine.explodes();
}
catch (e) {
exceptionMessage = e;
}
expect(exceptionMessage).toNotEqual(false);
});
});
suite.execute();
expect(exceptionMessage).toEqual('explodes function should not have been called');
});
});

187
spec/suites/SpyTest.js Normal file
View File

@@ -0,0 +1,187 @@
describe('Spies', function () {
it('should replace the specified function with a spy object', function() {
var originalFunctionWasCalled = false;
var TestClass = {
someFunction: function() {
originalFunctionWasCalled = true;
}
};
this.spyOn(TestClass, 'someFunction');
expect(TestClass.someFunction.wasCalled).toEqual(false);
expect(TestClass.someFunction.callCount).toEqual(0);
TestClass.someFunction('foo');
expect(TestClass.someFunction.wasCalled).toEqual(true);
expect(TestClass.someFunction.callCount).toEqual(1);
expect(TestClass.someFunction.mostRecentCall.args).toEqual(['foo']);
expect(TestClass.someFunction.mostRecentCall.object).toEqual(TestClass);
expect(originalFunctionWasCalled).toEqual(false);
TestClass.someFunction('bar');
expect(TestClass.someFunction.callCount).toEqual(2);
expect(TestClass.someFunction.mostRecentCall.args).toEqual(['bar']);
});
it('should allow you to view args for a particular call', function() {
var originalFunctionWasCalled = false;
var TestClass = {
someFunction: function() {
originalFunctionWasCalled = true;
}
};
this.spyOn(TestClass, 'someFunction');
TestClass.someFunction('foo');
TestClass.someFunction('bar');
expect(TestClass.someFunction.argsForCall[0]).toEqual(['foo']);
expect(TestClass.someFunction.argsForCall[1]).toEqual(['bar']);
expect(TestClass.someFunction.mostRecentCall.args).toEqual(['bar']);
});
it('should be possible to call through to the original method, or return a specific result', function() {
var originalFunctionWasCalled = false;
var passedArgs;
var passedObj;
var TestClass = {
someFunction: function() {
originalFunctionWasCalled = true;
passedArgs = arguments;
passedObj = this;
return "return value from original function";
}
};
this.spyOn(TestClass, 'someFunction').andCallThrough();
var result = TestClass.someFunction('arg1', 'arg2');
expect(result).toEqual("return value from original function");
expect(originalFunctionWasCalled).toEqual(true);
expect(passedArgs).toEqual(['arg1', 'arg2']);
expect(passedObj).toEqual(TestClass);
expect(TestClass.someFunction.wasCalled).toEqual(true);
});
it('should be possible to return a specific value', function() {
var originalFunctionWasCalled = false;
var TestClass = {
someFunction: function() {
originalFunctionWasCalled = true;
return "return value from original function";
}
};
this.spyOn(TestClass, 'someFunction').andReturn("some value");
originalFunctionWasCalled = false;
var result = TestClass.someFunction('arg1', 'arg2');
expect(result).toEqual("some value");
expect(originalFunctionWasCalled).toEqual(false);
});
it('should be possible to throw a specific error', function() {
var originalFunctionWasCalled = false;
var TestClass = {
someFunction: function() {
originalFunctionWasCalled = true;
return "return value from original function";
}
};
this.spyOn(TestClass, 'someFunction').andThrow(new Error('fake error'));
var exception;
try {
TestClass.someFunction('arg1', 'arg2');
} catch (e) {
exception = e;
}
expect(exception.message).toEqual('fake error');
expect(originalFunctionWasCalled).toEqual(false);
});
it('should be possible to call a specified function', function() {
var originalFunctionWasCalled = false;
var fakeFunctionWasCalled = false;
var passedArgs;
var passedObj;
var TestClass = {
someFunction: function() {
originalFunctionWasCalled = true;
return "return value from original function";
}
};
this.spyOn(TestClass, 'someFunction').andCallFake(function() {
fakeFunctionWasCalled = true;
passedArgs = arguments;
passedObj = this;
return "return value from fake function";
});
var result = TestClass.someFunction('arg1', 'arg2');
expect(result).toEqual("return value from fake function");
expect(originalFunctionWasCalled).toEqual(false);
expect(fakeFunctionWasCalled).toEqual(true);
expect(passedArgs).toEqual(['arg1', 'arg2']);
expect(passedObj).toEqual(TestClass);
expect(TestClass.someFunction.wasCalled).toEqual(true);
});
it('is torn down when this.removeAllSpies is called', function() {
var originalFunctionWasCalled = false;
var TestClass = {
someFunction: function() {
originalFunctionWasCalled = true;
}
};
this.spyOn(TestClass, 'someFunction');
TestClass.someFunction('foo');
expect(originalFunctionWasCalled).toEqual(false);
this.removeAllSpies();
TestClass.someFunction('foo');
expect(originalFunctionWasCalled).toEqual(true);
});
it('calls removeAllSpies during spec finish', function() {
var test = new jasmine.Spec({}, {}, 'sample test');
this.spyOn(test, 'removeAllSpies');
test.finish();
expect(test.removeAllSpies).wasCalled();
});
it('throws an exception when some method is spied on twice', function() {
var TestClass = { someFunction: function() {
} };
this.spyOn(TestClass, 'someFunction');
var exception;
try {
this.spyOn(TestClass, 'someFunction');
} catch (e) {
exception = e;
}
expect(exception).toBeDefined();
});
it('should be able to reset a spy', function() {
var TestClass = { someFunction: function() {} };
this.spyOn(TestClass, 'someFunction');
expect(TestClass.someFunction).wasNotCalled();
TestClass.someFunction();
expect(TestClass.someFunction).wasCalled();
TestClass.someFunction.reset();
expect(TestClass.someFunction).wasNotCalled();
expect(TestClass.someFunction.callCount).toEqual(0);
});
it("should create an object with a bunch of spy methods when you call jasmine.createSpyObj()", function() {
var spyObj = jasmine.createSpyObj('BaseName', ['method1', 'method2']);
expect(spyObj).toEqual({ method1: jasmine.any(Function), method2: jasmine.any(Function)});
expect(spyObj.method1.identity).toEqual('BaseName.method1');
expect(spyObj.method2.identity).toEqual('BaseName.method2');
});
});