Refactored into class files. Meta-tests and runner for jasmine. Stack traces available for Firefox and supported browsers. Experimental pretty print matcher support. Many other new features

This commit is contained in:
ragaskar 2009-05-28 20:02:15 -07:00
parent cabc666505
commit 9d95483de6
29 changed files with 3249 additions and 1717 deletions

View File

@ -13,10 +13,10 @@
</h1> </h1>
<div id="results"></div> <div id="results"></div>
<script type="text/javascript"> <script type="text/javascript">
Jasmine.getEnv().execute(); jasmine.getEnv().execute();
setTimeout(function () { setTimeout(function () {
document.getElementById('results').innerHTML = 'It\'s alive! :' + document.getElementById('results').innerHTML = 'It\'s alive! :' +
(Jasmine.getEnv().currentRunner.results.passedCount === 1); (jasmine.getEnv().currentRunner.getResults().passedCount === 1);
}, 250); }, 250);
</script> </script>
</body> </body>

View File

@ -1,7 +1,7 @@
describe('one suite description', function () { describe('one suite description', function () {
it('should be a test', function() { it('should be a test', function() {
runs(function () { runs(function () {
this.expects_that(true).should_equal(true); expect(true).toEqual(true);
}); });
}); });
}); });

61
lib/TrivialReporter.js Normal file
View File

@ -0,0 +1,61 @@
jasmine.TrivialReporter = function() {
};
jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) {
var el = document.createElement(type);
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
} else {
el.appendChild(child);
}
}
for (var attr in attrs) {
if (attr == 'className') {
el.setAttribute('class', attrs[attr]);
} else {
if (attr.indexOf('x-') == 0) {
el.setAttribute(attr, attrs[attr]);
} else {
el[attr] = attrs[attr];
}
}
}
return el;
};
jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) {
console.log(runner);
};
jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) {
console.log(suite);
};
jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) {
var specDiv = this.createDom('div', {
className: spec.getResults().passed() ? 'spec passed' : 'spec failed'
}, spec.getFullName());
var resultItems = spec.getResults().getItems();
for (var i = 0; i < resultItems.length; i++) {
var result = resultItems[i];
if (!result.passed) {
var resultMessageDiv = this.createDom('div', {className: 'resultMessage'});
resultMessageDiv.innerHTML = result.message; // todo: lame; mend
specDiv.appendChild(resultMessageDiv);
specDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
}
}
document.body.appendChild(specDiv);
};
jasmine.TrivialReporter.prototype.log = function() {
console.log.apply(console, arguments);
};

View File

@ -1,62 +1,35 @@
/* /*
* JasmineReporters.JSON -- * jasmine.Reporters.JSON --
* Basic reporter that keeps a JSON string of the most recent Spec, Suite or Runner * Basic reporter that keeps a JSON string of the most recent Spec, Suite or Runner
* result. Calling application can then do whatever it wants/needs with the string; * result. Calling application can then do whatever it wants/needs with the string;
*/ */
Jasmine.Reporters.JSON = function () { jasmine.Reporters.JSON = function () {
var toJSON = function(object){ var toJSON = function(object){
return JSON.stringify(object); return JSON.stringify(object);
}; };
var that = Jasmine.Reporters.reporter(); var that = jasmine.Reporters.reporter();
that.specJSON = ''; that.specJSON = '';
that.suiteJSON = ''; that.suiteJSON = '';
that.runnerJSON = ''; that.runnerJSON = '';
var saveSpecResults = function (results) { var saveSpecResults = function (spec) {
that.specJSON = toJSON(results); that.specJSON = toJSON(spec.getResults());
}; };
that.reportSpecResults = saveSpecResults; that.reportSpecResults = saveSpecResults;
var saveSuiteResults = function (results) { var saveSuiteResults = function (suite) {
that.suiteJSON = toJSON(results); that.suiteJSON = toJSON(suite.getResults());
}; };
that.reportSuiteResults = saveSuiteResults; that.reportSuiteResults = saveSuiteResults;
var saveRunnerResults = function (results) { var saveRunnerResults = function (runner) {
that.runnerJSON = toJSON(results); that.runnerJSON = toJSON(runner.getResults());
}; };
that.reportRunnerResults = saveRunnerResults; that.reportRunnerResults = saveRunnerResults;
this.log = function (str) {
console.log(str);
};
that.toJSON = toJSON; that.toJSON = toJSON;
return that; return that;
}; };
Jasmine.Reporters.domWriter = function (elementId) {
var that = {
element: document.getElementById(elementId),
write: function (text) {
if (that.element) {
that.element.innerHTML += text;
}
}
};
that.element.innerHTML = '';
return that;
};
Jasmine.Reporters.JSONtoDOM = function (elementId) {
var that = Jasmine.Reporters.JSON();
that.domWriter = Jasmine.Reporters.domWriter(elementId);
var writeRunnerResults = function (results) {
that.domWriter.write(that.toJSON(results));
};
that.reportRunnerResults = writeRunnerResults;
return that;
};

72
runner.html Normal file
View File

@ -0,0 +1,72 @@
<!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="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="test/json2.js"></script>
<script type="text/javascript" src="test/mock-timeout.js"></script>
<script type="text/javascript">
jasmine.include('test/JsonReporterTest.js', true);
jasmine.include('test/MatchersTest.js', true);
jasmine.include('test/NestedResultsTest.js', true);
jasmine.include('test/PrettyPrintTest.js', true);
jasmine.include('test/ReporterTest.js', true);
jasmine.include('test/RunnerTest.js', true);
jasmine.include('test/SpecRunningTest.js', true);
jasmine.include('test/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>

80
src/ActionCollection.js Normal file
View File

@ -0,0 +1,80 @@
/**
* base for Runner & Suite: allows for a queue of functions to get executed, allowing for
* any one action to complete, including asynchronous calls, before going to the next
* action.
*
* @constructor
* @param {jasmine.Env} env
*/
jasmine.ActionCollection = function(env) {
this.env = env;
this.actions = [];
this.index = 0;
this.finished = false;
};
jasmine.ActionCollection.prototype.finish = function() {
if (this.finishCallback) {
this.finishCallback();
}
this.finished = true;
};
jasmine.ActionCollection.prototype.execute = function() {
if (this.actions.length > 0) {
this.next();
}
};
jasmine.ActionCollection.prototype.getCurrentAction = function() {
return this.actions[this.index];
};
jasmine.ActionCollection.prototype.next = function() {
if (this.index >= this.actions.length) {
this.finish();
return;
}
var currentAction = this.getCurrentAction();
currentAction.execute(this);
if (currentAction.afterCallbacks) {
for (var i = 0; i < currentAction.afterCallbacks.length; i++) {
try {
currentAction.afterCallbacks[i]();
} catch (e) {
alert(e);
}
}
}
this.waitForDone(currentAction);
};
jasmine.ActionCollection.prototype.waitForDone = function(action) {
var self = this;
var afterExecute = function afterExecute() {
self.index++;
self.next();
};
if (action.finished) {
var now = new Date().getTime();
if (this.env.updateInterval && now - this.env.lastUpdate > this.env.updateInterval) {
this.env.lastUpdate = now;
this.env.setTimeout(afterExecute, 0);
} else {
afterExecute();
}
return;
}
var id = this.env.setInterval(function() {
if (action.finished) {
self.env.clearInterval(id);
afterExecute();
}
}, 150);
};

176
src/Env.js Normal file
View File

@ -0,0 +1,176 @@
/**
* Env
*
* @constructor
*/
jasmine.Env = function() {
this.currentSpec = null;
this.currentSuite = null;
this.currentRunner = new jasmine.Runner(this);
this.currentlyRunningTests = false;
this.updateInterval = 0;
this.lastUpdate = 0;
this.specFilter = function() {
return true;
};
this.nextSpecId_ = 0;
this.equalityTesters_ = [];
};
jasmine.Env.prototype.setTimeout = jasmine.setTimeout;
jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout;
jasmine.Env.prototype.setInterval = jasmine.setInterval;
jasmine.Env.prototype.clearInterval = jasmine.clearInterval;
jasmine.Env.prototype.execute = function() {
this.currentRunner.execute();
};
jasmine.Env.prototype.describe = function(description, specDefinitions) {
var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite);
var parentSuite = this.currentSuite;
if (parentSuite) {
parentSuite.specs.push(suite);
} else {
this.currentRunner.suites.push(suite);
}
this.currentSuite = suite;
specDefinitions.call(suite);
this.currentSuite = parentSuite;
return suite;
};
jasmine.Env.prototype.beforeEach = function(beforeEachFunction) {
this.currentSuite.beforeEach(beforeEachFunction);
};
jasmine.Env.prototype.afterEach = function(afterEachFunction) {
this.currentSuite.afterEach(afterEachFunction);
};
jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) {
return {
execute: function() {
}
};
};
jasmine.Env.prototype.it = function(description, func) {
var spec = new jasmine.Spec(this, this.currentSuite, description);
this.currentSuite.specs.push(spec);
this.currentSpec = spec;
if (func) {
spec.addToQueue(func);
}
return spec;
};
jasmine.Env.prototype.xit = function(desc, func) {
return {
id: this.nextSpecId_++,
runs: function() {
}
};
};
jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) {
if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) {
return true;
}
a.__Jasmine_been_here_before__ = b;
b.__Jasmine_been_here_before__ = a;
var hasKey = function(obj, keyName) {
return obj != null && obj[keyName] !== undefined;
};
for (var property in b) {
if (!hasKey(a, property) && hasKey(b, property)) {
mismatchKeys.push("expected has key '" + property + "', but missing from <b>actual</b>.");
}
}
for (property in a) {
if (!hasKey(b, property) && hasKey(a, property)) {
mismatchKeys.push("<b>expected</b> missing key '" + property + "', but present in actual.");
}
}
for (property in b) {
if (property == '__Jasmine_been_here_before__') continue;
if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) {
mismatchValues.push("'" + property + "' was<br /><br />'" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "'<br /><br />in expected, but was<br /><br />'" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "'<br /><br />in actual.<br />");
}
}
if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) {
mismatchValues.push("arrays were not the same length");
}
delete a.__Jasmine_been_here_before__;
delete b.__Jasmine_been_here_before__;
return (mismatchKeys.length == 0 && mismatchValues.length == 0);
};
jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) {
mismatchKeys = mismatchKeys || [];
mismatchValues = mismatchValues || [];
if (a === b) return true;
if (a === undefined || a === null || b === undefined || b === null) {
return (a == undefined && b == undefined);
}
if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) {
return a === b;
}
if (a instanceof Date && b instanceof Date) {
return a.getTime() == b.getTime();
}
if (a instanceof jasmine.Matchers.Any) {
return a.matches(b);
}
if (b instanceof jasmine.Matchers.Any) {
return b.matches(a);
}
if (typeof a === "object" && typeof b === "object") {
return this.compareObjects_(a, b, mismatchKeys, mismatchValues);
}
for (var i = 0; i < this.equalityTesters_.length; i++) {
var equalityTester = this.equalityTesters_[i];
var result = equalityTester(a, b, this, mismatchKeys, mismatchValues);
if (result !== undefined) return result;
}
//Straight check
return (a === b);
};
jasmine.Env.prototype.contains_ = function(haystack, needle) {
if (jasmine.isArray_(haystack)) {
for (var i = 0; i < haystack.length; i++) {
if (this.equals_(haystack[i], needle)) return true;
}
return false;
}
return haystack.indexOf(needle) >= 0;
};
jasmine.Env.prototype.addEqualityTester = function(equalityTester) {
this.equalityTesters_.push(equalityTester);
};

209
src/Matchers.js Normal file
View File

@ -0,0 +1,209 @@
/*
* jasmine.Matchers methods; add your own by extending jasmine.Matchers.prototype - don't forget to write a test
*
*/
jasmine.Matchers = function(env, actual, results) {
this.env = env;
this.actual = actual;
this.passing_message = 'Passed.';
this.results = results || new jasmine.NestedResults();
};
jasmine.Matchers.pp = function(str) {
return jasmine.util.htmlEscape(jasmine.pp(str));
};
jasmine.Matchers.prototype.getResults = function() {
return this.results;
};
jasmine.Matchers.prototype.report = function(result, failing_message, details) {
this.results.addResult(new jasmine.ExpectationResult(result, result ? this.passing_message : failing_message, details));
return result;
};
jasmine.Matchers.prototype.toBe = function(expected) {
return this.report(this.actual === expected, 'Expected<br /><br />' + jasmine.Matchers.pp(expected)
+ '<br /><br />to be the same object as<br /><br />' + jasmine.Matchers.pp(this.actual)
+ '<br />');
};
jasmine.Matchers.prototype.toNotBe = function(expected) {
return this.report(this.actual !== expected, 'Expected<br /><br />' + jasmine.Matchers.pp(expected)
+ '<br /><br />to be a different object from actual, but they were the same.');
};
jasmine.Matchers.prototype.toEqual = function(expected) {
var mismatchKeys = [];
var mismatchValues = [];
var formatMismatches = function(name, array) {
if (array.length == 0) return '';
var errorOutput = '<br /><br />Different ' + name + ':<br />';
for (var i = 0; i < array.length; i++) {
errorOutput += array[i] + '<br />';
}
return errorOutput;
};
return this.report(this.env.equals_(this.actual, expected, mismatchKeys, mismatchValues),
'Expected<br /><br />' + jasmine.Matchers.pp(expected)
+ '<br /><br />but got<br /><br />' + jasmine.Matchers.pp(this.actual)
+ '<br />'
+ formatMismatches('Keys', mismatchKeys)
+ formatMismatches('Values', mismatchValues), {
matcherName: 'toEqual', expected: expected, actual: this.actual
});
};
/** @deprecated */
jasmine.Matchers.prototype.should_equal = jasmine.Matchers.prototype.toEqual;
jasmine.Matchers.prototype.toNotEqual = function(expected) {
return this.report((this.actual !== expected),
'Expected ' + jasmine.Matchers.pp(expected) + ' to not equal ' + jasmine.Matchers.pp(this.actual) + ', but it does.');
};
/** @deprecated */
jasmine.Matchers.prototype.should_not_equal = jasmine.Matchers.prototype.toNotEqual;
jasmine.Matchers.prototype.toMatch = function(reg_exp) {
return this.report((new RegExp(reg_exp).test(this.actual)),
'Expected ' + jasmine.Matchers.pp(this.actual) + ' to match ' + reg_exp + '.');
};
/** @deprecated */
jasmine.Matchers.prototype.should_match = jasmine.Matchers.prototype.toMatch;
jasmine.Matchers.prototype.toNotMatch = function(reg_exp) {
return this.report((!new RegExp(reg_exp).test(this.actual)),
'Expected ' + jasmine.Matchers.pp(this.actual) + ' to not match ' + reg_exp + '.');
};
/** @deprecated */
jasmine.Matchers.prototype.should_not_match = jasmine.Matchers.prototype.toNotMatch;
jasmine.Matchers.prototype.toBeDefined = function() {
return this.report((this.actual !== undefined),
'Expected a value to be defined but it was undefined.');
};
/** @deprecated */
jasmine.Matchers.prototype.should_be_defined = jasmine.Matchers.prototype.toBeDefined;
jasmine.Matchers.prototype.toBeNull = function() {
return this.report((this.actual === null),
'Expected a value to be null but it was ' + jasmine.Matchers.pp(this.actual) + '.');
};
/** @deprecated */
jasmine.Matchers.prototype.should_be_null = jasmine.Matchers.prototype.toBeNull;
jasmine.Matchers.prototype.toBeTruthy = function() {
return this.report(!!this.actual,
'Expected a value to be truthy but it was ' + jasmine.Matchers.pp(this.actual) + '.');
};
/** @deprecated */
jasmine.Matchers.prototype.should_be_truthy = jasmine.Matchers.prototype.toBeTruthy;
jasmine.Matchers.prototype.toBeFalsy = function() {
return this.report(!this.actual,
'Expected a value to be falsy but it was ' + jasmine.Matchers.pp(this.actual) + '.');
};
/** @deprecated */
jasmine.Matchers.prototype.should_be_falsy = jasmine.Matchers.prototype.toBeFalsy;
jasmine.Matchers.prototype.wasCalled = function() {
if (!this.actual || !this.actual.isSpy) {
return this.report(false, 'Expected a spy, but got ' + jasmine.Matchers.pp(this.actual) + '.');
}
if (arguments.length > 0) {
return this.report(false, 'wasCalled matcher does not take arguments');
}
return this.report((this.actual.wasCalled),
'Expected spy "' + this.actual.identity + '" to have been called, but it was not.');
};
/** @deprecated */
jasmine.Matchers.prototype.was_called = jasmine.Matchers.prototype.wasCalled;
jasmine.Matchers.prototype.wasNotCalled = function() {
if (!this.actual || !this.actual.isSpy) {
return this.report(false, 'Expected a spy, but got ' + jasmine.Matchers.pp(this.actual) + '.');
}
return this.report((!this.actual.wasCalled),
'Expected spy "' + this.actual.identity + '" to not have been called, but it was.');
};
/** @deprecated */
jasmine.Matchers.prototype.was_not_called = jasmine.Matchers.prototype.wasNotCalled;
jasmine.Matchers.prototype.wasCalledWith = function() {
if (!this.actual || !this.actual.isSpy) {
return this.report(false, 'Expected a spy, but got ' + jasmine.Matchers.pp(this.actual) + '.', {
matcherName: 'wasCalledWith'
});
}
var args = jasmine.util.argsToArray(arguments);
return this.report(this.env.contains_(this.actual.argsForCall, args),
'Expected ' + jasmine.Matchers.pp(this.actual.argsForCall) + ' to contain ' + jasmine.Matchers.pp(args) + ', but it does not.', {
matcherName: 'wasCalledWith', expected: args, actual: this.actual.argsForCall
});
};
jasmine.Matchers.prototype.toContain = function(expected) {
return this.report(this.env.contains_(this.actual, expected),
'Expected ' + jasmine.Matchers.pp(this.actual) + ' to contain ' + jasmine.Matchers.pp(expected) + ', but it does not.', {
matcherName: 'toContain', expected: expected, actual: this.actual
});
};
jasmine.Matchers.prototype.toNotContain = function(item) {
return this.report(!this.env.contains_(this.actual, item),
'Expected ' + jasmine.Matchers.pp(this.actual) + ' not to contain ' + jasmine.Matchers.pp(item) + ', but it does.');
};
jasmine.Matchers.prototype.toThrow = function(expectedException) {
var exception = null;
try {
this.actual();
} catch (e) {
exception = e;
}
if (expectedException !== undefined) {
if (exception == null) {
return this.report(false, "Expected function to throw " + jasmine.Matchers.pp(expectedException) + ", but it did not.");
}
return this.report(
this.env.equals_(
exception.message || exception,
expectedException.message || expectedException),
"Expected function to throw " + jasmine.Matchers.pp(expectedException) + ", but it threw " + jasmine.Matchers.pp(exception) + ".");
} else {
return this.report(exception != null, "Expected function to throw an exception, but it did not.");
}
};
jasmine.Matchers.Any = function(expectedClass) {
this.expectedClass = expectedClass;
};
jasmine.Matchers.Any.prototype.matches = function(other) {
if (this.expectedClass == String) {
return typeof other == 'string' || other instanceof String;
}
if (this.expectedClass == Number) {
return typeof other == 'number' || other instanceof Number;
}
if (this.expectedClass == Function) {
return typeof other == 'function' || other instanceof Function;
}
if (this.expectedClass == Object) {
return typeof other == 'object';
}
return other instanceof this.expectedClass;
};
jasmine.Matchers.Any.prototype.toString = function() {
return '<jasmine.any(' + this.expectedClass + ')>';
};

49
src/NestedResults.js Normal file
View File

@ -0,0 +1,49 @@
/**
* Holds results; allows for the results array to hold another jasmine.NestedResults
*
* @constructor
*/
jasmine.NestedResults = function() {
this.totalCount = 0;
this.passedCount = 0;
this.failedCount = 0;
this.skipped = false;
this.items_ = [];
};
jasmine.NestedResults.prototype.rollupCounts = function(result) {
this.totalCount += result.totalCount;
this.passedCount += result.passedCount;
this.failedCount += result.failedCount;
};
jasmine.NestedResults.prototype.log = function(message) {
this.items_.push(new jasmine.MessageResult(message));
};
jasmine.NestedResults.prototype.getItems = function() {
return this.items_;
};
/**
* @param {jasmine.ExpectationResult|jasmine.NestedResults} result
*/
jasmine.NestedResults.prototype.addResult = function(result) {
if (result.type != 'MessageResult') {
if (result.items_) {
this.rollupCounts(result);
} else {
this.totalCount++;
if (result.passed) {
this.passedCount++;
} else {
this.failedCount++;
}
}
}
this.items_.push(result);
};
jasmine.NestedResults.prototype.passed = function() {
return this.passedCount === this.totalCount;
};

106
src/PrettyPrinter.js Normal file
View File

@ -0,0 +1,106 @@
jasmine.PrettyPrinter = function() {
this.ppNestLevel_ = 0;
};
jasmine.PrettyPrinter.prototype.format = function(value) {
if (this.ppNestLevel_ > 40) {
// return '(jasmine.pp nested too deeply!)';
throw new Error('jasmine.PrettyPrinter: format() nested too deeply!');
}
this.ppNestLevel_++;
try {
if (value === undefined) {
this.emitScalar('undefined');
} else if (value === null) {
this.emitScalar('null');
} else if (value.navigator && value.frames && value.setTimeout) {
this.emitScalar('<window>');
} else if (value instanceof jasmine.Matchers.Any) {
this.emitScalar(value.toString());
} else if (typeof value === 'string') {
this.emitScalar("'" + value + "'");
} else if (typeof value === 'function') {
this.emitScalar('Function');
} else if (typeof value.nodeType === 'number') {
this.emitScalar('HTMLNode');
} else if (value instanceof Date) {
this.emitScalar('Date(' + value + ')');
} else if (value.__Jasmine_been_here_before__) {
this.emitScalar('<circular reference: ' + (jasmine.isArray_(value) ? 'Array' : 'Object') + '>');
} else if (jasmine.isArray_(value) || typeof value == 'object') {
value.__Jasmine_been_here_before__ = true;
if (jasmine.isArray_(value)) {
this.emitArray(value);
} else {
this.emitObject(value);
}
delete value.__Jasmine_been_here_before__;
} else {
this.emitScalar(value.toString());
}
} finally {
this.ppNestLevel_--;
}
};
jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) {
for (var property in obj) {
if (property == '__Jasmine_been_here_before__') continue;
fn(property, obj.__lookupGetter__(property) != null);
}
};
jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_;
jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_;
jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_;
jasmine.StringPrettyPrinter = function() {
jasmine.PrettyPrinter.call(this);
this.string = '';
};
jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter);
jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) {
this.append(value);
};
jasmine.StringPrettyPrinter.prototype.emitArray = function(array) {
this.append('[ ');
for (var i = 0; i < array.length; i++) {
if (i > 0) {
this.append(', ');
}
this.format(array[i]);
}
this.append(' ]');
};
jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) {
var self = this;
this.append('{ ');
var first = true;
this.iterateObject(obj, function(property, isGetter) {
if (first) {
first = false;
} else {
self.append(', ');
}
self.append(property);
self.append(' : ');
if (isGetter) {
self.append('<getter>');
} else {
self.format(obj[property]);
}
});
this.append(' }');
};
jasmine.StringPrettyPrinter.prototype.append = function(value) {
this.string += value;
};

86
src/QueuedFunction.js Normal file
View File

@ -0,0 +1,86 @@
/**
* QueuedFunction is how ActionCollections' actions are implemented
*
* @constructor
* @param {jasmine.Env} env
* @param {Function} func
* @param {Number} timeout
* @param {Function} latchFunction
* @param {jasmine.Spec} spec
*/
jasmine.QueuedFunction = function(env, func, timeout, latchFunction, spec) {
this.env = env;
this.func = func;
this.timeout = timeout;
this.latchFunction = latchFunction;
this.spec = spec;
this.totalTimeSpentWaitingForLatch = 0;
this.latchTimeoutIncrement = 100;
};
jasmine.QueuedFunction.prototype.next = function() {
this.spec.finish(); // default value is to be done after one function
};
jasmine.QueuedFunction.prototype.safeExecute = function() {
if (this.env.reporter) {
this.env.reporter.log('>> Jasmine Running ' + this.spec.suite.description + ' ' + this.spec.description + '...');
}
try {
this.func.apply(this.spec);
} catch (e) {
this.fail(e);
}
};
jasmine.QueuedFunction.prototype.execute = function() {
var self = this;
var executeNow = function() {
self.safeExecute();
self.next();
};
var executeLater = function() {
self.env.setTimeout(executeNow, self.timeout);
};
var executeNowOrLater = function() {
var latchFunctionResult;
try {
latchFunctionResult = self.latchFunction.apply(self.spec);
} catch (e) {
self.fail(e);
self.next();
return;
}
if (latchFunctionResult) {
executeNow();
} else if (self.totalTimeSpentWaitingForLatch >= self.timeout) {
var message = 'timed out after ' + self.timeout + ' msec waiting for ' + (self.latchFunction.description || 'something to happen');
self.fail({
name: 'timeout',
message: message
});
self.next();
} else {
self.totalTimeSpentWaitingForLatch += self.latchTimeoutIncrement;
self.env.setTimeout(executeNowOrLater, self.latchTimeoutIncrement);
}
};
if (this.latchFunction !== undefined) {
executeNowOrLater();
} else if (this.timeout > 0) {
executeLater();
} else {
executeNow();
}
};
jasmine.QueuedFunction.prototype.fail = function(e) {
this.spec.results.addResult(new jasmine.ExpectationResult(false, jasmine.util.formatException(e), null));
};

33
src/Reporters.js Normal file
View File

@ -0,0 +1,33 @@
/* JasmineReporters.reporter
* Base object that will get called whenever a Spec, Suite, or Runner is done. It is up to
* descendants of this object to do something with the results (see json_reporter.js)
*/
jasmine.Reporters = {};
jasmine.Reporters.reporter = function(callbacks) {
var that = {
callbacks: callbacks || {},
doCallback: function(callback, results) {
if (callback) {
callback(results);
}
},
reportRunnerResults: function(runner) {
that.doCallback(that.callbacks.runnerCallback, runner);
},
reportSuiteResults: function(suite) {
that.doCallback(that.callbacks.suiteCallback, suite);
},
reportSpecResults: function(spec) {
that.doCallback(that.callbacks.specCallback, spec);
},
log: function (str) {
if (console && console.log) console.log(str);
}
};
return that;
};

26
src/Runner.js Normal file
View File

@ -0,0 +1,26 @@
/**
* Runner
*
* @constructor
* @param {jasmine.Env} env
*/
jasmine.Runner = function(env) {
jasmine.ActionCollection.call(this, env);
this.suites = this.actions;
};
jasmine.util.inherit(jasmine.Runner, jasmine.ActionCollection);
jasmine.Runner.prototype.finishCallback = function() {
if (this.env.reporter) {
this.env.reporter.reportRunnerResults(this);
}
};
jasmine.Runner.prototype.getResults = function() {
var results = new jasmine.NestedResults();
for (var i = 0; i < this.suites.length; i++) {
results.rollupCounts(this.suites[i].getResults());
}
return results;
};

175
src/Spec.js Normal file
View File

@ -0,0 +1,175 @@
/**
* Spec
*
* @constructor
* @param {jasmine.Env} env
* @param {String} description
*/
jasmine.Spec = function(env, suite, description) {
this.id = env.nextSpecId_++;
this.env = env;
this.suite = suite;
this.description = description;
this.queue = [];
this.currentTimeout = 0;
this.currentLatchFunction = undefined;
this.finished = false;
this.afterCallbacks = [];
this.spies_ = [];
this.results = new jasmine.NestedResults();
this.results.description = description;
this.runs = this.addToQueue;
};
jasmine.Spec.prototype.getFullName = function() {
return this.suite.getFullName() + ' ' + this.description + '.';
};
jasmine.Spec.prototype.getResults = function() {
return this.results;
};
jasmine.Spec.prototype.addToQueue = function(func) {
var queuedFunction = new jasmine.QueuedFunction(this.env, func, this.currentTimeout, this.currentLatchFunction, this);
this.queue.push(queuedFunction);
if (this.queue.length > 1) {
var previousQueuedFunction = this.queue[this.queue.length - 2];
previousQueuedFunction.next = function() {
queuedFunction.execute();
};
}
this.resetTimeout();
return this;
};
/** @deprecated */
jasmine.Spec.prototype.expects_that = function(actual) {
return this.expect(actual);
};
jasmine.Spec.prototype.expect = function(actual) {
return new jasmine.Matchers(this.env, actual, this.results);
};
jasmine.Spec.prototype.waits = function(timeout) {
this.currentTimeout = timeout;
this.currentLatchFunction = undefined;
return this;
};
jasmine.Spec.prototype.waitsFor = function(timeout, latchFunction, message) {
this.currentTimeout = timeout;
this.currentLatchFunction = latchFunction;
this.currentLatchFunction.description = message;
return this;
};
jasmine.Spec.prototype.resetTimeout = function() {
this.currentTimeout = 0;
this.currentLatchFunction = undefined;
};
jasmine.Spec.prototype.finishCallback = function() {
if (this.env.reporter) {
this.env.reporter.reportSpecResults(this);
}
};
jasmine.Spec.prototype.finish = function() {
this.safeExecuteAfters();
this.removeAllSpies();
this.finishCallback();
this.finished = true;
};
jasmine.Spec.prototype.after = function(doAfter) {
this.afterCallbacks.unshift(doAfter);
};
jasmine.Spec.prototype.execute = function() {
if (!this.env.specFilter(this)) {
this.results.skipped = true;
this.finishCallback();
this.finished = true;
return;
}
this.env.currentSpec = this;
this.env.currentlyRunningTests = true;
this.safeExecuteBefores();
if (this.queue[0]) {
this.queue[0].execute();
} else {
this.finish();
}
this.env.currentlyRunningTests = false;
};
jasmine.Spec.prototype.safeExecuteBefores = function() {
var befores = [];
for (var suite = this.suite; suite; suite = suite.parentSuite) {
if (suite.beforeEachFunction) befores.push(suite.beforeEachFunction);
}
while (befores.length) {
this.safeExecuteBeforeOrAfter(befores.pop());
}
};
jasmine.Spec.prototype.safeExecuteAfters = function() {
for (var suite = this.suite; suite; suite = suite.parentSuite) {
if (suite.afterEachFunction) this.safeExecuteBeforeOrAfter(suite.afterEachFunction);
}
};
jasmine.Spec.prototype.safeExecuteBeforeOrAfter = function(func) {
try {
func.apply(this);
} catch (e) {
this.results.addResult(new jasmine.ExpectationResult(false, func.typeName + '() fail: ' + jasmine.util.formatException(e), null));
}
};
jasmine.Spec.prototype.explodes = function() {
throw 'explodes function should not have been called';
};
jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) {
if (obj == undefined) {
throw "spyOn could not find an object to spy upon for " + methodName + "()";
}
if (!ignoreMethodDoesntExist && obj[methodName] === undefined) {
throw methodName + '() method does not exist';
}
if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) {
throw new Error(methodName + ' has already been spied upon');
}
var spyObj = jasmine.createSpy(methodName);
this.spies_.push(spyObj);
spyObj.baseObj = obj;
spyObj.methodName = methodName;
spyObj.originalValue = obj[methodName];
obj[methodName] = spyObj;
return spyObj;
};
jasmine.Spec.prototype.removeAllSpies = function() {
for (var i = 0; i < this.spies_.length; i++) {
var spy = this.spies_[i];
spy.baseObj[spy.methodName] = spy.originalValue;
}
this.spies_ = [];
};

53
src/Suite.js Normal file
View File

@ -0,0 +1,53 @@
/**
* Description
*
* @constructor
* @param {jasmine.Env} env
* @param {String} description
* @param {Function} specDefinitions
* @param {jasmine.Suite} parentSuite
*/
jasmine.Suite = function(env, description, specDefinitions, parentSuite) {
jasmine.ActionCollection.call(this, env);
this.description = description;
this.specs = this.actions;
this.parentSuite = parentSuite;
this.beforeEachFunction = null;
this.afterEachFunction = null;
};
jasmine.util.inherit(jasmine.Suite, jasmine.ActionCollection);
jasmine.Suite.prototype.getFullName = function() {
var fullName = this.description;
for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) {
fullName = parentSuite.description + ' ' + fullName;
}
return fullName;
};
jasmine.Suite.prototype.finishCallback = function() {
if (this.env.reporter) {
this.env.reporter.reportSuiteResults(this);
}
};
jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) {
beforeEachFunction.typeName = 'beforeEach';
this.beforeEachFunction = beforeEachFunction;
};
jasmine.Suite.prototype.afterEach = function(afterEachFunction) {
afterEachFunction.typeName = 'afterEach';
this.afterEachFunction = afterEachFunction;
};
jasmine.Suite.prototype.getResults = function() {
var results = new jasmine.NestedResults();
for (var i = 0; i < this.specs.length; i++) {
results.rollupCounts(this.specs[i].getResults());
}
return results;
};

213
src/base.js Executable file
View File

@ -0,0 +1,213 @@
/*
* Jasmine internal classes & objects
*/
/** @namespace */
var jasmine = {};
/** @deprecated use jasmine (lowercase because it's a package name) instead */
var Jasmine = jasmine;
jasmine.unimplementedMethod_ = function() {
throw new Error("unimplemented method");
};
jasmine.bindOriginal_ = function(base, name) {
var original = base[name];
return function() {
return original.apply(base, arguments);
};
};
jasmine.setTimeout = jasmine.bindOriginal_(window, 'setTimeout');
jasmine.clearTimeout = jasmine.bindOriginal_(window, 'clearTimeout');
jasmine.setInterval = jasmine.bindOriginal_(window, 'setInterval');
jasmine.clearInterval = jasmine.bindOriginal_(window, 'clearInterval');
jasmine.MessageResult = function(text) {
this.type = 'MessageResult';
this.text = text;
this.trace = new Error(); // todo: test better
};
jasmine.ExpectationResult = function(passed, message, details) {
this.type = 'ExpectationResult';
this.passed = passed;
this.message = message;
this.details = details;
this.trace = new Error(message); // todo: test better
};
jasmine.getEnv = function() {
return jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env();
};
jasmine.isArray_ = function(value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
jasmine.pp = function(value) {
var stringPrettyPrinter = new jasmine.StringPrettyPrinter();
stringPrettyPrinter.format(value);
return stringPrettyPrinter.string;
};
jasmine.isDomNode = function(obj) {
return obj['nodeType'] > 0;
};
jasmine.any = function(clazz) {
return new jasmine.Matchers.Any(clazz);
};
jasmine.createSpy = function(name) {
var spyObj = function() {
spyObj.wasCalled = true;
spyObj.callCount++;
var args = jasmine.util.argsToArray(arguments);
spyObj.mostRecentCall = {
object: this,
args: args
};
spyObj.argsForCall.push(args);
return spyObj.plan.apply(this, arguments);
};
spyObj.identity = name || 'unknown';
spyObj.isSpy = true;
spyObj.plan = function() {
};
spyObj.andCallThrough = function() {
spyObj.plan = spyObj.originalValue;
return spyObj;
};
spyObj.andReturn = function(value) {
spyObj.plan = function() {
return value;
};
return spyObj;
};
spyObj.andThrow = function(exceptionMsg) {
spyObj.plan = function() {
throw exceptionMsg;
};
return spyObj;
};
spyObj.andCallFake = function(fakeFunc) {
spyObj.plan = fakeFunc;
return spyObj;
};
spyObj.reset = function() {
spyObj.wasCalled = false;
spyObj.callCount = 0;
spyObj.argsForCall = [];
spyObj.mostRecentCall = {};
};
spyObj.reset();
return spyObj;
};
jasmine.createSpyObj = function(baseName, methodNames) {
var obj = {};
for (var i = 0; i < methodNames.length; i++) {
obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]);
}
return obj;
};
jasmine.log = function(message) {
jasmine.getEnv().currentSpec.getResults().log(message);
};
var spyOn = function(obj, methodName) {
return jasmine.getEnv().currentSpec.spyOn(obj, methodName);
};
var it = function(desc, func) {
return jasmine.getEnv().it(desc, func);
};
//this mirrors the spec syntax so you can define a spec description that will not run.
var xit = function(desc, func) {
return jasmine.getEnv().xit(desc, func);
};
var expect = function(actual) {
return jasmine.getEnv().currentSpec.expect(actual);
};
var runs = function(func) {
jasmine.getEnv().currentSpec.runs(func);
};
var waits = function(timeout) {
jasmine.getEnv().currentSpec.waits(timeout);
};
var waitsFor = function(timeout, latchFunction, message) {
jasmine.getEnv().currentSpec.waitsFor(timeout, latchFunction, message);
};
var beforeEach = function(beforeEachFunction) {
jasmine.getEnv().beforeEach(beforeEachFunction);
};
var afterEach = function(afterEachFunction) {
jasmine.getEnv().afterEach(afterEachFunction);
};
var describe = function(description, specDefinitions) {
return jasmine.getEnv().describe(description, specDefinitions);
};
var xdescribe = function(description, specDefinitions) {
return jasmine.getEnv().xdescribe(description, specDefinitions);
};
jasmine.XmlHttpRequest = XMLHttpRequest;
// Provide the XMLHttpRequest class for IE 5.x-6.x:
if (typeof XMLHttpRequest == "undefined") jasmine.XmlHttpRequest = function() {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch(e) {
}
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch(e) {
}
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
}
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
}
throw new Error("This browser does not support XMLHttpRequest.");
};
jasmine.include = function(url, opt_global) {
if (opt_global) {
document.write('<script type="text/javascript" src="' + url + '"></' + 'script>');
} else {
var xhr;
try {
xhr = new jasmine.XmlHttpRequest();
xhr.open("GET", url, false);
xhr.send(null);
} catch(e) {
throw new Error("couldn't fetch " + url + ": " + e);
}
return eval(xhr.responseText);
}
};

50
src/util.js Normal file
View File

@ -0,0 +1,50 @@
/** @namespace */
jasmine.util = {};
jasmine.util.inherit = function(childClass, parentClass) {
var subclass = function() {
};
subclass.prototype = parentClass.prototype;
childClass.prototype = new subclass;
};
jasmine.util.formatException = function(e) {
var lineNumber;
if (e.line) {
lineNumber = e.line;
}
else if (e.lineNumber) {
lineNumber = e.lineNumber;
}
var file;
if (e.sourceURL) {
file = e.sourceURL;
}
else if (e.fileName) {
file = e.fileName;
}
var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString();
if (file && lineNumber) {
message += ' in ' + file + ' (line ' + lineNumber + ')';
}
return message;
};
jasmine.util.htmlEscape = function(str) {
if (!str) return str;
return str.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
};
jasmine.util.argsToArray = function(args) {
var arrayOfArgs = [];
for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]);
return arrayOfArgs;
};

53
test/JsonReporterTest.js Normal file
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
test/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);
});
});

41
test/NestedResultsTest.js Normal file
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);
});
});

62
test/PrettyPrintTest.js Normal file
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>");
});
});

58
test/ReporterTest.js Normal file
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
test/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);
});
});

712
test/SpecRunningTest.js Normal file
View File

@ -0,0 +1,712 @@
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 = xdescribe('a disabled suite', function() {
it('enabled spec, but should not be run', function() {
spy();
});
});
disabledSuite.execute();
expect(spy).wasNotCalled();
});
});

187
test/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');
});
});

View File

@ -6,8 +6,20 @@
<!--<script type="text/javascript" src="prototype-1.6.0.3.js"></script>--> <!--<script type="text/javascript" src="prototype-1.6.0.3.js"></script>-->
<script type="text/javascript" src="json2.js"></script> <script type="text/javascript" src="json2.js"></script>
<script type="text/javascript" src="jsUnitMockTimeout.js"></script> <script type="text/javascript" src="jsUnitMockTimeout.js"></script>
<script type="text/javascript" src="../lib/jasmine.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="../lib/json_reporter.js"></script>
<script type="text/javascript" src="mock-timeout.js"></script>
<link type="text/css" rel="stylesheet" href="../lib/jasmine.css"/> <link type="text/css" rel="stylesheet" href="../lib/jasmine.css"/>
<script type="text/javascript" src="bootstrap.js"></script> <script type="text/javascript" src="bootstrap.js"></script>
</head> </head>

1771
test/bootstrap.js vendored

File diff suppressed because it is too large Load Diff

57
test/mock-ajax.js Normal file
View File

@ -0,0 +1,57 @@
jasmine.AjaxRequests = {
requests: $A(),
activeRequest: function() {
return this.requests.last();
},
add: function(request) {
this.requests.push(request);
var spec = jasmine.getEnv().currentSpec;
spec.after(function() { jasmine.AjaxRequests.clear(); });
},
remove: function(request) {
this.requests = this.requests.without(request);
},
clear: function() {
this.requests.clear();
}
};
jasmine.AjaxRequest = Class.create(Ajax.Request, {
request: function(url) {
this.url = url;
this.method = this.options.method;
var params = Object.clone(this.options.parameters);
if (!['get', 'post'].include(this.method)) {
// simulate other verbs over post
params['_method'] = this.method;
this.method = 'post';
}
this.parameters = params;
if (params = Object.toQueryString(params)) {
// when GET, append parameters to URL
if (this.method == 'get')
this.url += (this.url.include('?') ? '&' : '?') + params;
else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
params += '&_=';
}
jasmine.AjaxRequests.add(this);
},
response: function(response) {
if (!response.status || response.status == 200 || response.status == "200") {
if (this.options.onSuccess) {this.options.onSuccess(response);}
} else {
if (this.options.onFailure) {this.options.onFailure(response);}
}
if (this.options.onComplete) {this.options.onComplete(response);}
jasmine.AjaxRequests.remove(this);
}
});

158
test/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);
};