Inject a per-runable pretty printer into MatchersUtil

This will allow us to add support for custom object formatters, which
will be a per-runable resource like custom matchers, by injecting them
into the pretty-printer.
This commit is contained in:
Steve Gravrock
2019-10-08 22:57:07 -07:00
committed by Steve Gravrock
parent dec67bd535
commit 1f23f1e4d2
46 changed files with 546 additions and 401 deletions
+131 -109
View File
@@ -76,15 +76,19 @@ var getJasmineRequireObj = (function(jasmineGlobal) {
j$.asymmetricEqualityTesterArgCompatShim = jRequire.asymmetricEqualityTesterArgCompatShim( j$.asymmetricEqualityTesterArgCompatShim = jRequire.asymmetricEqualityTesterArgCompatShim(
j$ j$
); );
j$.makePrettyPrinter = jRequire.makePrettyPrinter(j$);
j$.pp = j$.makePrettyPrinter();
j$.MatchersUtil = jRequire.MatchersUtil(j$); j$.MatchersUtil = jRequire.MatchersUtil(j$);
j$.matchersUtil = new j$.MatchersUtil({ customTesters: [] }); j$.matchersUtil = new j$.MatchersUtil({
customTesters: [],
pp: j$.pp
});
j$.ObjectContaining = jRequire.ObjectContaining(j$); j$.ObjectContaining = jRequire.ObjectContaining(j$);
j$.ArrayContaining = jRequire.ArrayContaining(j$); j$.ArrayContaining = jRequire.ArrayContaining(j$);
j$.ArrayWithExactContents = jRequire.ArrayWithExactContents(j$); j$.ArrayWithExactContents = jRequire.ArrayWithExactContents(j$);
j$.MapContaining = jRequire.MapContaining(j$); j$.MapContaining = jRequire.MapContaining(j$);
j$.SetContaining = jRequire.SetContaining(j$); j$.SetContaining = jRequire.SetContaining(j$);
j$.pp = jRequire.pp(j$);
j$.QueueRunner = jRequire.QueueRunner(j$); j$.QueueRunner = jRequire.QueueRunner(j$);
j$.ReportDispatcher = jRequire.ReportDispatcher(j$); j$.ReportDispatcher = jRequire.ReportDispatcher(j$);
j$.Spec = jRequire.Spec(j$); j$.Spec = jRequire.Spec(j$);
@@ -1226,12 +1230,25 @@ getJasmineRequireObj().Env = function(j$) {
return 'suite' + nextSuiteId++; return 'suite' + nextSuiteId++;
}; };
var makePrettyPrinter = function() {
return j$.makePrettyPrinter();
};
var makeMatchersUtil = function() {
var customEqualityTesters =
runnableResources[currentRunnable().id].customEqualityTesters;
return new j$.MatchersUtil({
customTesters: customEqualityTesters,
pp: makePrettyPrinter()
});
};
var expectationFactory = function(actual, spec) { var expectationFactory = function(actual, spec) {
var customEqualityTesters = var customEqualityTesters =
runnableResources[spec.id].customEqualityTesters; runnableResources[spec.id].customEqualityTesters;
return j$.Expectation.factory({ return j$.Expectation.factory({
util: new j$.MatchersUtil({ customTesters: customEqualityTesters }), util: makeMatchersUtil(),
customEqualityTesters: customEqualityTesters, customEqualityTesters: customEqualityTesters,
customMatchers: runnableResources[spec.id].customMatchers, customMatchers: runnableResources[spec.id].customMatchers,
actual: actual, actual: actual,
@@ -1244,11 +1261,8 @@ getJasmineRequireObj().Env = function(j$) {
}; };
var asyncExpectationFactory = function(actual, spec) { var asyncExpectationFactory = function(actual, spec) {
var customEqualityTesters =
runnableResources[spec.id].customEqualityTesters;
return j$.Expectation.asyncFactory({ return j$.Expectation.asyncFactory({
util: new j$.MatchersUtil({ customTesters: customEqualityTesters }), util: makeMatchersUtil(),
customEqualityTesters: runnableResources[spec.id].customEqualityTesters, customEqualityTesters: runnableResources[spec.id].customEqualityTesters,
customAsyncMatchers: runnableResources[spec.id].customAsyncMatchers, customAsyncMatchers: runnableResources[spec.id].customAsyncMatchers,
actual: actual, actual: actual,
@@ -2060,7 +2074,7 @@ getJasmineRequireObj().Env = function(j$) {
message += error; message += error;
} else { } else {
// pretty print all kind of objects. This includes arrays. // pretty print all kind of objects. This includes arrays.
message += j$.pp(error); message += makePrettyPrinter()(error);
} }
} }
@@ -3543,7 +3557,7 @@ getJasmineRequireObj().Expectation = function(j$) {
args = args.slice(); args = args.slice();
args.unshift(true); args.unshift(true);
args.unshift(matcherName); args.unshift(matcherName);
return util.buildFailureMessage.apply(null, args); return util.buildFailureMessage.apply(util, args);
} }
function negate(result) { function negate(result) {
@@ -3761,7 +3775,7 @@ getJasmineRequireObj().Expector = function(j$) {
var args = self.args.slice(); var args = self.args.slice();
args.unshift(false); args.unshift(false);
args.unshift(self.matcherName); args.unshift(self.matcherName);
return self.util.buildFailureMessage.apply(null, args); return self.util.buildFailureMessage.apply(self.util, args);
} else if (j$.isFunction_(result.message)) { } else if (j$.isFunction_(result.message)) {
return result.message(); return result.message();
} else { } else {
@@ -3941,7 +3955,7 @@ getJasmineRequireObj().toBeRejectedWith = function(j$) {
* @example * @example
* return expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); * return expectAsync(aPromise).toBeRejectedWith({prop: 'value'});
*/ */
return function toBeRejectedWith(util) { return function toBeRejectedWith(matchersUtil) {
return { return {
compare: function(actualPromise, expectedValue) { compare: function(actualPromise, expectedValue) {
if (!j$.isPromiseLike(actualPromise)) { if (!j$.isPromiseLike(actualPromise)) {
@@ -3951,7 +3965,7 @@ getJasmineRequireObj().toBeRejectedWith = function(j$) {
function prefix(passed) { function prefix(passed) {
return 'Expected a promise ' + return 'Expected a promise ' +
(passed ? 'not ' : '') + (passed ? 'not ' : '') +
'to be rejected with ' + j$.pp(expectedValue); 'to be rejected with ' + matchersUtil.pp(expectedValue);
} }
return actualPromise.then( return actualPromise.then(
@@ -3962,7 +3976,7 @@ getJasmineRequireObj().toBeRejectedWith = function(j$) {
}; };
}, },
function(actualValue) { function(actualValue) {
if (util.equals(actualValue, expectedValue)) { if (matchersUtil.equals(actualValue, expectedValue)) {
return { return {
pass: true, pass: true,
message: prefix(true) + '.' message: prefix(true) + '.'
@@ -3970,7 +3984,7 @@ getJasmineRequireObj().toBeRejectedWith = function(j$) {
} else { } else {
return { return {
pass: false, pass: false,
message: prefix(false) + ' but it was rejected with ' + j$.pp(actualValue) + '.' message: prefix(false) + ' but it was rejected with ' + matchersUtil.pp(actualValue) + '.'
}; };
} }
} }
@@ -3996,14 +4010,14 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) {
* await expectAsync(aPromise).toBeRejectedWithError('Error message'); * await expectAsync(aPromise).toBeRejectedWithError('Error message');
* return expectAsync(aPromise).toBeRejectedWithError(/Error message/); * return expectAsync(aPromise).toBeRejectedWithError(/Error message/);
*/ */
return function toBeRejectedWithError() { return function toBeRejectedWithError(matchersUtil) {
return { return {
compare: function(actualPromise, arg1, arg2) { compare: function(actualPromise, arg1, arg2) {
if (!j$.isPromiseLike(actualPromise)) { if (!j$.isPromiseLike(actualPromise)) {
throw new Error('Expected toBeRejectedWithError to be called on a promise.'); throw new Error('Expected toBeRejectedWithError to be called on a promise.');
} }
var expected = getExpectedFromArgs(arg1, arg2); var expected = getExpectedFromArgs(arg1, arg2, matchersUtil);
return actualPromise.then( return actualPromise.then(
function() { function() {
@@ -4012,15 +4026,15 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) {
message: 'Expected a promise to be rejected but it was resolved.' message: 'Expected a promise to be rejected but it was resolved.'
}; };
}, },
function(actualValue) { return matchError(actualValue, expected); } function(actualValue) { return matchError(actualValue, expected, matchersUtil); }
); );
} }
}; };
}; };
function matchError(actual, expected) { function matchError(actual, expected, matchersUtil) {
if (!j$.isError_(actual)) { if (!j$.isError_(actual)) {
return fail(expected, 'rejected with ' + j$.pp(actual)); return fail(expected, 'rejected with ' + matchersUtil.pp(actual));
} }
if (!(actual instanceof expected.error)) { if (!(actual instanceof expected.error)) {
@@ -4037,7 +4051,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) {
return pass(expected); return pass(expected);
} }
return fail(expected, 'rejected with ' + j$.pp(actual)); return fail(expected, 'rejected with ' + matchersUtil.pp(actual));
} }
function pass(expected) { function pass(expected) {
@@ -4055,7 +4069,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) {
} }
function getExpectedFromArgs(arg1, arg2) { function getExpectedFromArgs(arg1, arg2, matchersUtil) {
var error, message; var error, message;
if (isErrorConstructor(arg1)) { if (isErrorConstructor(arg1)) {
@@ -4069,7 +4083,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) {
return { return {
error: error, error: error,
message: message, message: message,
printValue: j$.fnNameFor(error) + (typeof message === 'undefined' ? '' : ': ' + j$.pp(message)) printValue: j$.fnNameFor(error) + (typeof message === 'undefined' ? '' : ': ' + matchersUtil.pp(message))
}; };
} }
@@ -4119,7 +4133,7 @@ getJasmineRequireObj().toBeResolvedTo = function(j$) {
* @example * @example
* return expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); * return expectAsync(aPromise).toBeResolvedTo({prop: 'value'});
*/ */
return function toBeResolvedTo(util) { return function toBeResolvedTo(matchersUtil) {
return { return {
compare: function(actualPromise, expectedValue) { compare: function(actualPromise, expectedValue) {
if (!j$.isPromiseLike(actualPromise)) { if (!j$.isPromiseLike(actualPromise)) {
@@ -4129,12 +4143,12 @@ getJasmineRequireObj().toBeResolvedTo = function(j$) {
function prefix(passed) { function prefix(passed) {
return 'Expected a promise ' + return 'Expected a promise ' +
(passed ? 'not ' : '') + (passed ? 'not ' : '') +
'to be resolved to ' + j$.pp(expectedValue); 'to be resolved to ' + matchersUtil.pp(expectedValue);
} }
return actualPromise.then( return actualPromise.then(
function(actualValue) { function(actualValue) {
if (util.equals(actualValue, expectedValue)) { if (matchersUtil.equals(actualValue, expectedValue)) {
return { return {
pass: true, pass: true,
message: prefix(true) + '.' message: prefix(true) + '.'
@@ -4142,7 +4156,7 @@ getJasmineRequireObj().toBeResolvedTo = function(j$) {
} else { } else {
return { return {
pass: false, pass: false,
message: prefix(false) + ' but it was resolved to ' + j$.pp(actualValue) + '.' message: prefix(false) + ' but it was resolved to ' + matchersUtil.pp(actualValue) + '.'
}; };
} }
}, },
@@ -4193,16 +4207,13 @@ getJasmineRequireObj().DiffBuilder = function(j$) {
}; };
getJasmineRequireObj().MatchersUtil = function(j$) { getJasmineRequireObj().MatchersUtil = function(j$) {
// TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter? // TODO: convert all uses of j$.pp to use the injected pp
function MatchersUtil(options) { function MatchersUtil(options) {
options = options || {}; options = options || {};
this.customTesters_ = options.customTesters || []; this.customTesters_ = options.customTesters || [];
this.pp = options.pp || function() {};
if (!j$.isArray_(this.customTesters_)) { };
throw new Error("MatchersUtil requires custom equality testers");
}
}
MatchersUtil.prototype.contains = function(haystack, needle, customTesters) { MatchersUtil.prototype.contains = function(haystack, needle, customTesters) {
if (j$.isSet(haystack)) { if (j$.isSet(haystack)) {
@@ -4224,6 +4235,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
}; };
MatchersUtil.prototype.buildFailureMessage = function() { MatchersUtil.prototype.buildFailureMessage = function() {
var self = this;
var args = Array.prototype.slice.call(arguments, 0), var args = Array.prototype.slice.call(arguments, 0),
matcherName = args[0], matcherName = args[0],
isNot = args[1], isNot = args[1],
@@ -4232,7 +4244,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); });
var message = 'Expected ' + var message = 'Expected ' +
j$.pp(actual) + self.pp(actual) +
(isNot ? ' not ' : ' ') + (isNot ? ' not ' : ' ') +
englishyPredicate; englishyPredicate;
@@ -4434,7 +4446,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
for (i = 0; i < aLength || i < bLength; i++) { for (i = 0; i < aLength || i < bLength; i++) {
diffBuilder.withPath(i, function() { diffBuilder.withPath(i, function() {
if (i >= bLength) { if (i >= bLength) {
diffBuilder.record(a[i], void 0, actualArrayIsLongerFormatter); diffBuilder.record(a[i], void 0, actualArrayIsLongerFormatter.bind(null, self.pp));
result = false; result = false;
} else { } else {
result = self.eq_(i < aLength ? a[i] : void 0, i < bLength ? b[i] : void 0, aStack, bStack, customTesters, diffBuilder) && result; result = self.eq_(i < aLength ? a[i] : void 0, i < bLength ? b[i] : void 0, aStack, bStack, customTesters, diffBuilder) && result;
@@ -4551,7 +4563,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
a instanceof aCtor && b instanceof bCtor && a instanceof aCtor && b instanceof bCtor &&
!(aCtor instanceof aCtor && bCtor instanceof bCtor)) { !(aCtor instanceof aCtor && bCtor instanceof bCtor)) {
diffBuilder.record(a, b, constructorsAreDifferentFormatter); diffBuilder.record(a, b, constructorsAreDifferentFormatter.bind(null, this.pp));
return false; return false;
} }
} }
@@ -4562,7 +4574,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
// Ensure that both objects contain the same number of properties before comparing deep equality. // Ensure that both objects contain the same number of properties before comparing deep equality.
if (keys(b, className == '[object Array]').length !== size) { if (keys(b, className == '[object Array]').length !== size) {
diffBuilder.record(a, b, objectKeysAreDifferentFormatter); diffBuilder.record(a, b, objectKeysAreDifferentFormatter.bind(null, this.pp));
return false; return false;
} }
@@ -4570,7 +4582,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
key = aKeys[i]; key = aKeys[i];
// Deep compare each member // Deep compare each member
if (!j$.util.has(b, key)) { if (!j$.util.has(b, key)) {
diffBuilder.record(a, b, objectKeysAreDifferentFormatter); diffBuilder.record(a, b, objectKeysAreDifferentFormatter.bind(null, this.pp));
result = false; result = false;
continue; continue;
} }
@@ -4627,11 +4639,11 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
return typeof obj === 'function'; return typeof obj === 'function';
} }
function objectKeysAreDifferentFormatter(actual, expected, path) { function objectKeysAreDifferentFormatter(pp, actual, expected, path) {
var missingProperties = j$.util.objectDifference(expected, actual), var missingProperties = j$.util.objectDifference(expected, actual),
extraProperties = j$.util.objectDifference(actual, expected), extraProperties = j$.util.objectDifference(actual, expected),
missingPropertiesMessage = formatKeyValuePairs(missingProperties), missingPropertiesMessage = formatKeyValuePairs(pp, missingProperties),
extraPropertiesMessage = formatKeyValuePairs(extraProperties), extraPropertiesMessage = formatKeyValuePairs(pp, extraProperties),
messages = []; messages = [];
if (!path.depth()) { if (!path.depth()) {
@@ -4649,7 +4661,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
return messages.join('\n'); return messages.join('\n');
} }
function constructorsAreDifferentFormatter(actual, expected, path) { function constructorsAreDifferentFormatter(pp, actual, expected, path) {
if (!path.depth()) { if (!path.depth()) {
path = 'object'; path = 'object';
} }
@@ -4657,20 +4669,20 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
return 'Expected ' + return 'Expected ' +
path + ' to be a kind of ' + path + ' to be a kind of ' +
j$.fnNameFor(expected.constructor) + j$.fnNameFor(expected.constructor) +
', but was ' + j$.pp(actual) + '.'; ', but was ' + pp(actual) + '.';
} }
function actualArrayIsLongerFormatter(actual, expected, path) { function actualArrayIsLongerFormatter(pp, actual, expected, path) {
return 'Unexpected ' + return 'Unexpected ' +
path + (path.depth() ? ' = ' : '') + path + (path.depth() ? ' = ' : '') +
j$.pp(actual) + pp(actual) +
' in array.'; ' in array.';
} }
function formatKeyValuePairs(obj) { function formatKeyValuePairs(pp, obj) {
var formatted = ''; var formatted = '';
for (var key in obj) { for (var key in obj) {
formatted += '\n ' + key + ': ' + j$.pp(obj[key]); formatted += '\n ' + key + ': ' + pp(obj[key]);
} }
return formatted; return formatted;
} }
@@ -4977,11 +4989,11 @@ getJasmineRequireObj().toBeInstanceOf = function(j$) {
* expect(3).toBeInstanceOf(Number); * expect(3).toBeInstanceOf(Number);
* expect(new Error()).toBeInstanceOf(Error); * expect(new Error()).toBeInstanceOf(Error);
*/ */
function toBeInstanceOf() { function toBeInstanceOf(matchersUtil) {
return { return {
compare: function(actual, expected) { compare: function(actual, expected) {
var actualType = actual && actual.constructor ? j$.fnNameFor(actual.constructor) : j$.pp(actual), var actualType = actual && actual.constructor ? j$.fnNameFor(actual.constructor) : matchersUtil.pp(actual),
expectedType = expected ? j$.fnNameFor(expected) : j$.pp(expected), expectedType = expected ? j$.fnNameFor(expected) : matchersUtil.pp(expected),
expectedMatcher, expectedMatcher,
pass; pass;
@@ -5067,7 +5079,7 @@ getJasmineRequireObj().toBeNaN = function(j$) {
* @example * @example
* expect(thing).toBeNaN(); * expect(thing).toBeNaN();
*/ */
function toBeNaN() { function toBeNaN(matchersUtil) {
return { return {
compare: function(actual) { compare: function(actual) {
var result = { var result = {
@@ -5077,7 +5089,7 @@ getJasmineRequireObj().toBeNaN = function(j$) {
if (result.pass) { if (result.pass) {
result.message = 'Expected actual not to be NaN.'; result.message = 'Expected actual not to be NaN.';
} else { } else {
result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be NaN.'; }; result.message = function() { return 'Expected ' + matchersUtil.pp(actual) + ' to be NaN.'; };
} }
return result; return result;
@@ -5097,7 +5109,7 @@ getJasmineRequireObj().toBeNegativeInfinity = function(j$) {
* @example * @example
* expect(thing).toBeNegativeInfinity(); * expect(thing).toBeNegativeInfinity();
*/ */
function toBeNegativeInfinity() { function toBeNegativeInfinity(matchersUtil) {
return { return {
compare: function(actual) { compare: function(actual) {
var result = { var result = {
@@ -5107,7 +5119,7 @@ getJasmineRequireObj().toBeNegativeInfinity = function(j$) {
if (result.pass) { if (result.pass) {
result.message = 'Expected actual not to be -Infinity.'; result.message = 'Expected actual not to be -Infinity.';
} else { } else {
result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be -Infinity.'; }; result.message = function() { return 'Expected ' + matchersUtil.pp(actual) + ' to be -Infinity.'; };
} }
return result; return result;
@@ -5149,7 +5161,7 @@ getJasmineRequireObj().toBePositiveInfinity = function(j$) {
* @example * @example
* expect(thing).toBePositiveInfinity(); * expect(thing).toBePositiveInfinity();
*/ */
function toBePositiveInfinity() { function toBePositiveInfinity(matchersUtil) {
return { return {
compare: function(actual) { compare: function(actual) {
var result = { var result = {
@@ -5159,7 +5171,7 @@ getJasmineRequireObj().toBePositiveInfinity = function(j$) {
if (result.pass) { if (result.pass) {
result.message = 'Expected actual not to be Infinity.'; result.message = 'Expected actual not to be Infinity.';
} else { } else {
result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be Infinity.'; }; result.message = function() { return 'Expected ' + matchersUtil.pp(actual) + ' to be Infinity.'; };
} }
return result; return result;
@@ -5305,13 +5317,13 @@ getJasmineRequireObj().toHaveBeenCalled = function(j$) {
* expect(mySpy).toHaveBeenCalled(); * expect(mySpy).toHaveBeenCalled();
* expect(mySpy).not.toHaveBeenCalled(); * expect(mySpy).not.toHaveBeenCalled();
*/ */
function toHaveBeenCalled() { function toHaveBeenCalled(matchersUtil) {
return { return {
compare: function(actual) { compare: function(actual) {
var result = {}; var result = {};
if (!j$.isSpy(actual)) { if (!j$.isSpy(actual)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); throw new Error(getErrorMsg('Expected a spy, but got ' + matchersUtil.pp(actual) + '.'));
} }
if (arguments.length > 1) { if (arguments.length > 1) {
@@ -5345,14 +5357,14 @@ getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) {
* @example * @example
* expect(mySpy).toHaveBeenCalledBefore(otherSpy); * expect(mySpy).toHaveBeenCalledBefore(otherSpy);
*/ */
function toHaveBeenCalledBefore() { function toHaveBeenCalledBefore(matchersUtil) {
return { return {
compare: function(firstSpy, latterSpy) { compare: function(firstSpy, latterSpy) {
if (!j$.isSpy(firstSpy)) { if (!j$.isSpy(firstSpy)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(firstSpy) + '.')); throw new Error(getErrorMsg('Expected a spy, but got ' + matchersUtil.pp(firstSpy) + '.'));
} }
if (!j$.isSpy(latterSpy)) { if (!j$.isSpy(latterSpy)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(latterSpy) + '.')); throw new Error(getErrorMsg('Expected a spy, but got ' + matchersUtil.pp(latterSpy) + '.'));
} }
var result = { pass: false }; var result = { pass: false };
@@ -5407,11 +5419,11 @@ getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) {
* @example * @example
* expect(mySpy).toHaveBeenCalledTimes(3); * expect(mySpy).toHaveBeenCalledTimes(3);
*/ */
function toHaveBeenCalledTimes() { function toHaveBeenCalledTimes(matchersUtil) {
return { return {
compare: function(actual, expected) { compare: function(actual, expected) {
if (!j$.isSpy(actual)) { if (!j$.isSpy(actual)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); throw new Error(getErrorMsg('Expected a spy, but got ' + matchersUtil.pp(actual) + '.'));
} }
var args = Array.prototype.slice.call(arguments, 0), var args = Array.prototype.slice.call(arguments, 0),
@@ -5449,7 +5461,7 @@ getJasmineRequireObj().toHaveBeenCalledWith = function(j$) {
* @example * @example
* expect(mySpy).toHaveBeenCalledWith('foo', 'bar', 2); * expect(mySpy).toHaveBeenCalledWith('foo', 'bar', 2);
*/ */
function toHaveBeenCalledWith(util) { function toHaveBeenCalledWith(matchersUtil) {
return { return {
compare: function() { compare: function() {
var args = Array.prototype.slice.call(arguments, 0), var args = Array.prototype.slice.call(arguments, 0),
@@ -5458,40 +5470,40 @@ getJasmineRequireObj().toHaveBeenCalledWith = function(j$) {
result = { pass: false }; result = { pass: false };
if (!j$.isSpy(actual)) { if (!j$.isSpy(actual)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); throw new Error(getErrorMsg('Expected a spy, but got ' + matchersUtil.pp(actual) + '.'));
} }
if (!actual.calls.any()) { if (!actual.calls.any()) {
result.message = function() { result.message = function() {
return 'Expected spy ' + actual.and.identity + ' to have been called with:\n' + return 'Expected spy ' + actual.and.identity + ' to have been called with:\n' +
' ' + j$.pp(expectedArgs) + ' ' + matchersUtil.pp(expectedArgs) +
'\nbut it was never called.'; '\nbut it was never called.';
}; };
return result; return result;
} }
if (util.contains(actual.calls.allArgs(), expectedArgs)) { if (matchersUtil.contains(actual.calls.allArgs(), expectedArgs)) {
result.pass = true; result.pass = true;
result.message = function() { result.message = function() {
return 'Expected spy ' + actual.and.identity + ' not to have been called with:\n' + return 'Expected spy ' + actual.and.identity + ' not to have been called with:\n' +
' ' + j$.pp(expectedArgs) + ' ' + matchersUtil.pp(expectedArgs) +
'\nbut it was.'; '\nbut it was.';
}; };
} else { } else {
result.message = function() { result.message = function() {
var prettyPrintedCalls = actual.calls.allArgs().map(function(argsForCall) { var prettyPrintedCalls = actual.calls.allArgs().map(function(argsForCall) {
return ' ' + j$.pp(argsForCall); return ' ' + matchersUtil.pp(argsForCall);
}); });
var diffs = actual.calls.allArgs().map(function(argsForCall, callIx) { var diffs = actual.calls.allArgs().map(function(argsForCall, callIx) {
var diffBuilder = new j$.DiffBuilder(); var diffBuilder = new j$.DiffBuilder();
util.equals(argsForCall, expectedArgs, diffBuilder); matchersUtil.equals(argsForCall, expectedArgs, diffBuilder);
return 'Call ' + callIx + ':\n' + return 'Call ' + callIx + ':\n' +
diffBuilder.getMessage().replace(/^/mg, ' '); diffBuilder.getMessage().replace(/^/mg, ' ');
}); });
return 'Expected spy ' + actual.and.identity + ' to have been called with:\n' + return 'Expected spy ' + actual.and.identity + ' to have been called with:\n' +
' ' + j$.pp(expectedArgs) + '\n' + '' + ' ' + matchersUtil.pp(expectedArgs) + '\n' + '' +
'but actual calls were:\n' + 'but actual calls were:\n' +
prettyPrintedCalls.join(',\n') + '.\n\n' + prettyPrintedCalls.join(',\n') + '.\n\n' +
diffs.join('\n'); diffs.join('\n');
@@ -5518,11 +5530,11 @@ getJasmineRequireObj().toHaveClass = function(j$) {
* el.className = 'foo bar baz'; * el.className = 'foo bar baz';
* expect(el).toHaveClass('bar'); * expect(el).toHaveClass('bar');
*/ */
function toHaveClass() { function toHaveClass(matchersUtil) {
return { return {
compare: function(actual, expected) { compare: function(actual, expected) {
if (!isElement(actual)) { if (!isElement(actual)) {
throw new Error(j$.pp(actual) + ' is not a DOM element'); throw new Error(matchersUtil.pp(actual) + ' is not a DOM element');
} }
return { return {
@@ -5588,7 +5600,7 @@ getJasmineRequireObj().toThrow = function(j$) {
* expect(function() { return 'things'; }).toThrow('foo'); * expect(function() { return 'things'; }).toThrow('foo');
* expect(function() { return 'stuff'; }).toThrow(); * expect(function() { return 'stuff'; }).toThrow();
*/ */
function toThrow(util) { function toThrow(matchersUtil) {
return { return {
compare: function(actual, expected) { compare: function(actual, expected) {
var result = { pass: false }, var result = { pass: false },
@@ -5613,16 +5625,16 @@ getJasmineRequireObj().toThrow = function(j$) {
if (arguments.length == 1) { if (arguments.length == 1) {
result.pass = true; result.pass = true;
result.message = function() { return 'Expected function not to throw, but it threw ' + j$.pp(thrown) + '.'; }; result.message = function() { return 'Expected function not to throw, but it threw ' + matchersUtil.pp(thrown) + '.'; };
return result; return result;
} }
if (util.equals(thrown, expected)) { if (matchersUtil.equals(thrown, expected)) {
result.pass = true; result.pass = true;
result.message = function() { return 'Expected function not to throw ' + j$.pp(expected) + '.'; }; result.message = function() { return 'Expected function not to throw ' + matchersUtil.pp(expected) + '.'; };
} else { } else {
result.message = function() { return 'Expected function to throw ' + j$.pp(expected) + ', but it threw ' + j$.pp(thrown) + '.'; }; result.message = function() { return 'Expected function to throw ' + matchersUtil.pp(expected) + ', but it threw ' + matchersUtil.pp(thrown) + '.'; };
} }
return result; return result;
@@ -5651,7 +5663,7 @@ getJasmineRequireObj().toThrowError = function(j$) {
* expect(function() { return 'other'; }).toThrowError(/foo/); * expect(function() { return 'other'; }).toThrowError(/foo/);
* expect(function() { return 'other'; }).toThrowError(); * expect(function() { return 'other'; }).toThrowError();
*/ */
function toThrowError () { function toThrowError(matchersUtil) {
return { return {
compare: function(actual) { compare: function(actual) {
var errorMatcher = getMatcher.apply(null, arguments), var errorMatcher = getMatcher.apply(null, arguments),
@@ -5669,7 +5681,7 @@ getJasmineRequireObj().toThrowError = function(j$) {
} }
if (!j$.isError_(thrown)) { if (!j$.isError_(thrown)) {
return fail(function() { return 'Expected function to throw an Error, but it threw ' + j$.pp(thrown) + '.'; }); return fail(function() { return 'Expected function to throw an Error, but it threw ' + matchersUtil.pp(thrown) + '.'; });
} }
return errorMatcher.match(thrown); return errorMatcher.match(thrown);
@@ -5732,7 +5744,7 @@ getJasmineRequireObj().toThrowError = function(j$) {
thrownMessage = ''; thrownMessage = '';
if (expected) { if (expected) {
thrownMessage = ' with message ' + j$.pp(thrown.message); thrownMessage = ' with message ' + matchersUtil.pp(thrown.message);
} }
return thrownName + thrownMessage; return thrownName + thrownMessage;
@@ -5742,9 +5754,9 @@ getJasmineRequireObj().toThrowError = function(j$) {
if (expected === null) { if (expected === null) {
return ''; return '';
} else if (expected instanceof RegExp) { } else if (expected instanceof RegExp) {
return ' with a message matching ' + j$.pp(expected); return ' with a message matching ' + matchersUtil.pp(expected);
} else { } else {
return ' with message ' + j$.pp(expected); return ' with message ' + matchersUtil.pp(expected);
} }
} }
@@ -5813,7 +5825,7 @@ getJasmineRequireObj().toThrowMatching = function(j$) {
* @example * @example
* expect(function() { throw new Error('nope'); }).toThrowMatching(function(thrown) { return thrown.message === 'nope'; }); * expect(function() { throw new Error('nope'); }).toThrowMatching(function(thrown) { return thrown.message === 'nope'; });
*/ */
function toThrowMatching() { function toThrowMatching(matchersUtil) {
return { return {
compare: function(actual, predicate) { compare: function(actual, predicate) {
var thrown; var thrown;
@@ -5843,14 +5855,14 @@ getJasmineRequireObj().toThrowMatching = function(j$) {
} }
} }
}; };
}
function thrownDescription(thrown) { function thrownDescription(thrown) {
if (thrown && thrown.constructor) { if (thrown && thrown.constructor) {
return j$.fnNameFor(thrown.constructor) + ' with message ' + return j$.fnNameFor(thrown.constructor) + ' with message ' +
j$.pp(thrown.message); matchersUtil.pp(thrown.message);
} else { } else {
return j$.pp(thrown); return matchersUtil.pp(thrown);
}
} }
} }
@@ -5977,8 +5989,8 @@ getJasmineRequireObj().MockDate = function() {
return MockDate; return MockDate;
}; };
getJasmineRequireObj().pp = function(j$) { getJasmineRequireObj().makePrettyPrinter = function(j$) {
function PrettyPrinter() { function SinglePrettyPrintRun() {
this.ppNestLevel_ = 0; this.ppNestLevel_ = 0;
this.seen = []; this.seen = [];
this.length = 0; this.length = 0;
@@ -6000,7 +6012,7 @@ getJasmineRequireObj().pp = function(j$) {
} }
} }
PrettyPrinter.prototype.format = function(value) { SinglePrettyPrintRun.prototype.format = function(value) {
this.ppNestLevel_++; this.ppNestLevel_++;
try { try {
if (j$.util.isUndefined(value)) { if (j$.util.isUndefined(value)) {
@@ -6074,7 +6086,7 @@ getJasmineRequireObj().pp = function(j$) {
} }
}; };
PrettyPrinter.prototype.iterateObject = function(obj, fn) { SinglePrettyPrintRun.prototype.iterateObject = function(obj, fn) {
var objKeys = keys(obj, j$.isArray_(obj)); var objKeys = keys(obj, j$.isArray_(obj));
var isGetter = function isGetter(prop) {}; var isGetter = function isGetter(prop) {};
@@ -6093,15 +6105,15 @@ getJasmineRequireObj().pp = function(j$) {
return objKeys.length > length; return objKeys.length > length;
}; };
PrettyPrinter.prototype.emitScalar = function(value) { SinglePrettyPrintRun.prototype.emitScalar = function(value) {
this.append(value); this.append(value);
}; };
PrettyPrinter.prototype.emitString = function(value) { SinglePrettyPrintRun.prototype.emitString = function(value) {
this.append("'" + value + "'"); this.append("'" + value + "'");
}; };
PrettyPrinter.prototype.emitArray = function(array) { SinglePrettyPrintRun.prototype.emitArray = function(array) {
if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) {
this.append('Array'); this.append('Array');
return; return;
@@ -6137,7 +6149,7 @@ getJasmineRequireObj().pp = function(j$) {
this.append(' ]'); this.append(' ]');
}; };
PrettyPrinter.prototype.emitSet = function(set) { SinglePrettyPrintRun.prototype.emitSet = function(set) {
if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) {
this.append('Set'); this.append('Set');
return; return;
@@ -6162,7 +6174,7 @@ getJasmineRequireObj().pp = function(j$) {
this.append(' )'); this.append(' )');
}; };
PrettyPrinter.prototype.emitMap = function(map) { SinglePrettyPrintRun.prototype.emitMap = function(map) {
if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) {
this.append('Map'); this.append('Map');
return; return;
@@ -6187,7 +6199,7 @@ getJasmineRequireObj().pp = function(j$) {
this.append(' )'); this.append(' )');
}; };
PrettyPrinter.prototype.emitObject = function(obj) { SinglePrettyPrintRun.prototype.emitObject = function(obj) {
var ctor = obj.constructor, var ctor = obj.constructor,
constructorName; constructorName;
@@ -6223,7 +6235,7 @@ getJasmineRequireObj().pp = function(j$) {
this.append(' })'); this.append(' })');
}; };
PrettyPrinter.prototype.emitTypedArray = function(arr) { SinglePrettyPrintRun.prototype.emitTypedArray = function(arr) {
var constructorName = j$.fnNameFor(arr.constructor), var constructorName = j$.fnNameFor(arr.constructor),
limitedArray = Array.prototype.slice.call( limitedArray = Array.prototype.slice.call(
arr, arr,
@@ -6239,7 +6251,7 @@ getJasmineRequireObj().pp = function(j$) {
this.append(constructorName + ' [ ' + itemsString + ' ]'); this.append(constructorName + ' [ ' + itemsString + ' ]');
}; };
PrettyPrinter.prototype.emitDomElement = function(el) { SinglePrettyPrintRun.prototype.emitDomElement = function(el) {
var tagName = el.tagName.toLowerCase(), var tagName = el.tagName.toLowerCase(),
attrs = el.attributes, attrs = el.attributes,
i, i,
@@ -6265,7 +6277,11 @@ getJasmineRequireObj().pp = function(j$) {
this.append(out); this.append(out);
}; };
PrettyPrinter.prototype.formatProperty = function(obj, property, isGetter) { SinglePrettyPrintRun.prototype.formatProperty = function(
obj,
property,
isGetter
) {
this.append(property); this.append(property);
this.append(': '); this.append(': ');
if (isGetter) { if (isGetter) {
@@ -6275,7 +6291,7 @@ getJasmineRequireObj().pp = function(j$) {
} }
}; };
PrettyPrinter.prototype.append = function(value) { SinglePrettyPrintRun.prototype.append = function(value) {
// This check protects us from the rare case where an object has overriden // This check protects us from the rare case where an object has overriden
// `toString()` with an invalid implementation (returning a non-string). // `toString()` with an invalid implementation (returning a non-string).
if (typeof value !== 'string') { if (typeof value !== 'string') {
@@ -6339,10 +6355,13 @@ getJasmineRequireObj().pp = function(j$) {
return extraKeys; return extraKeys;
} }
return function(value) {
var prettyPrinter = new PrettyPrinter(); return function() {
prettyPrinter.format(value); return function(value) {
return prettyPrinter.stringParts.join(''); var prettyPrinter = new SinglePrettyPrintRun();
prettyPrinter.format(value);
return prettyPrinter.stringParts.join('');
};
}; };
}; };
@@ -7033,7 +7052,10 @@ getJasmineRequireObj().Spy = function(j$) {
}; };
})(); })();
var matchersUtil = new j$.MatchersUtil(); var matchersUtil = new j$.MatchersUtil({
customTesters: [],
pp: j$.makePrettyPrinter()
});
/** /**
* _Note:_ Do not construct this directly, use {@link spyOn}, {@link spyOnProperty}, {@link jasmine.createSpy}, or {@link jasmine.createSpyObj} * _Note:_ Do not construct this directly, use {@link spyOn}, {@link spyOnProperty}, {@link jasmine.createSpy}, or {@link jasmine.createSpyObj}
+10 -5
View File
@@ -24,8 +24,9 @@ describe('AsyncExpectation', function() {
var addExpectationResult = jasmine.createSpy('addExpectationResult'), var addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = Promise.resolve(), actual = Promise.resolve(),
pp = jasmineUnderTest.makePrettyPrinter(),
expectation = jasmineUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
util: new jasmineUnderTest.MatchersUtil(), util: new jasmineUnderTest.MatchersUtil({ pp: pp }),
actual: actual, actual: actual,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
}); });
@@ -47,7 +48,7 @@ describe('AsyncExpectation', function() {
var addExpectationResult = jasmine.createSpy('addExpectationResult'), var addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = Promise.reject(), actual = Promise.reject(),
expectation = jasmineUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
util: new jasmineUnderTest.MatchersUtil(), util: new jasmineUnderTest.MatchersUtil({ pp: function() {} }),
actual: actual, actual: actual,
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
}); });
@@ -122,7 +123,8 @@ describe('AsyncExpectation', function() {
var util = { var util = {
buildFailureMessage: function() { buildFailureMessage: function() {
return 'failure message'; return 'failure message';
} },
pp: jasmineUnderTest.makePrettyPrinter()
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
expectation = jasmineUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
@@ -180,10 +182,11 @@ describe('AsyncExpectation', function() {
var addExpectationResult = jasmine.createSpy('addExpectationResult'), var addExpectationResult = jasmine.createSpy('addExpectationResult'),
actual = Promise.resolve(), actual = Promise.resolve(),
pp = jasmineUnderTest.makePrettyPrinter(),
expectation = jasmineUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: actual, actual: actual,
addExpectationResult: addExpectationResult, addExpectationResult: addExpectationResult,
util: new jasmineUnderTest.MatchersUtil() util: new jasmineUnderTest.MatchersUtil({ pp: pp })
}); });
return expectation return expectation
@@ -208,7 +211,9 @@ describe('AsyncExpectation', function() {
expectation = jasmineUnderTest.Expectation.asyncFactory({ expectation = jasmineUnderTest.Expectation.asyncFactory({
actual: actual, actual: actual,
addExpectationResult: addExpectationResult, addExpectationResult: addExpectationResult,
util: new jasmineUnderTest.MatchersUtil() util: new jasmineUnderTest.MatchersUtil({
pp: jasmineUnderTest.makePrettyPrinter()
})
}); });
return expectation return expectation
+8 -2
View File
@@ -307,10 +307,12 @@ describe('Env', function() {
it('creates an expectationFactory that uses the current custom equality testers', function(done) { it('creates an expectationFactory that uses the current custom equality testers', function(done) {
function customEqualityTester() {} function customEqualityTester() {}
function prettyPrinter() {}
var RealSpec = jasmineUnderTest.Spec, var RealSpec = jasmineUnderTest.Spec,
specInstance, specInstance,
expectationFactory; expectationFactory;
spyOn(jasmineUnderTest, 'MatchersUtil'); spyOn(jasmineUnderTest, 'MatchersUtil');
spyOn(jasmineUnderTest, 'makePrettyPrinter').and.returnValue(prettyPrinter);
spyOn(jasmineUnderTest, 'Spec').and.callFake(function(options) { spyOn(jasmineUnderTest, 'Spec').and.callFake(function(options) {
expectationFactory = options.expectationFactory; expectationFactory = options.expectationFactory;
specInstance = new RealSpec(options); specInstance = new RealSpec(options);
@@ -325,7 +327,8 @@ describe('Env', function() {
env.addReporter({ env.addReporter({
jasmineDone: function() { jasmineDone: function() {
expect(jasmineUnderTest.MatchersUtil).toHaveBeenCalledWith({ expect(jasmineUnderTest.MatchersUtil).toHaveBeenCalledWith({
customTesters: [customEqualityTester] customTesters: [customEqualityTester],
pp: prettyPrinter
}); });
done(); done();
} }
@@ -336,10 +339,12 @@ describe('Env', function() {
it('creates an asyncExpectationFactory that uses the current custom equality testers', function(done) { it('creates an asyncExpectationFactory that uses the current custom equality testers', function(done) {
function customEqualityTester() {} function customEqualityTester() {}
function prettyPrinter() {}
var RealSpec = jasmineUnderTest.Spec, var RealSpec = jasmineUnderTest.Spec,
specInstance, specInstance,
asyncExpectationFactory; asyncExpectationFactory;
spyOn(jasmineUnderTest, 'MatchersUtil'); spyOn(jasmineUnderTest, 'MatchersUtil');
spyOn(jasmineUnderTest, 'makePrettyPrinter').and.returnValue(prettyPrinter);
spyOn(jasmineUnderTest, 'Spec').and.callFake(function(options) { spyOn(jasmineUnderTest, 'Spec').and.callFake(function(options) {
asyncExpectationFactory = options.asyncExpectationFactory; asyncExpectationFactory = options.asyncExpectationFactory;
specInstance = new RealSpec(options); specInstance = new RealSpec(options);
@@ -354,7 +359,8 @@ describe('Env', function() {
env.addReporter({ env.addReporter({
jasmineDone: function() { jasmineDone: function() {
expect(jasmineUnderTest.MatchersUtil).toHaveBeenCalledWith({ expect(jasmineUnderTest.MatchersUtil).toHaveBeenCalledWith({
customTesters: [customEqualityTester] customTesters: [customEqualityTester],
pp: prettyPrinter
}); });
done(); done();
} }
+2 -1
View File
@@ -632,9 +632,10 @@ describe('Expectation', function() {
} }
}, },
addExpectationResult = jasmine.createSpy('addExpectationResult'), addExpectationResult = jasmine.createSpy('addExpectationResult'),
pp = jasmineUnderTest.makePrettyPrinter(),
expectation = jasmineUnderTest.Expectation.factory({ expectation = jasmineUnderTest.Expectation.factory({
customMatchers: matchers, customMatchers: matchers,
util: new jasmineUnderTest.MatchersUtil(), util: new jasmineUnderTest.MatchersUtil({ pp: pp }),
actual: 'an actual', actual: 'an actual',
addExpectationResult: addExpectationResult addExpectationResult: addExpectationResult
}); });
+97 -89
View File
@@ -1,17 +1,19 @@
describe('jasmineUnderTest.pp', function() { describe('PrettyPrinter', function() {
it('should wrap strings in single quotes', function() { it('should wrap strings in single quotes', function() {
expect(jasmineUnderTest.pp('some string')).toEqual("'some string'"); var pp = jasmineUnderTest.makePrettyPrinter();
expect(jasmineUnderTest.pp("som' string")).toEqual("'som' string'"); expect(pp('some string')).toEqual("'some string'");
expect(pp("som' string")).toEqual("'som' string'");
}); });
it('should stringify primitives properly', function() { it('should stringify primitives properly', function() {
expect(jasmineUnderTest.pp(true)).toEqual('true'); var pp = jasmineUnderTest.makePrettyPrinter();
expect(jasmineUnderTest.pp(false)).toEqual('false'); expect(pp(true)).toEqual('true');
expect(jasmineUnderTest.pp(null)).toEqual('null'); expect(pp(false)).toEqual('false');
expect(jasmineUnderTest.pp(jasmine.undefined)).toEqual('undefined'); expect(pp(null)).toEqual('null');
expect(jasmineUnderTest.pp(3)).toEqual('3'); expect(pp(jasmine.undefined)).toEqual('undefined');
expect(jasmineUnderTest.pp(-3.14)).toEqual('-3.14'); expect(pp(3)).toEqual('3');
expect(jasmineUnderTest.pp(-0)).toEqual('-0'); expect(pp(-3.14)).toEqual('-3.14');
expect(pp(-0)).toEqual('-0');
}); });
describe('stringify sets', function() { describe('stringify sets', function() {
@@ -20,7 +22,8 @@ describe('jasmineUnderTest.pp', function() {
var set = new Set(); var set = new Set();
set.add(1); set.add(1);
set.add(2); set.add(2);
expect(jasmineUnderTest.pp(set)).toEqual('Set( 1, 2 )'); var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(set)).toEqual('Set( 1, 2 )');
}); });
it('should truncate sets with more elements than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() { it('should truncate sets with more elements than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() {
@@ -33,7 +36,8 @@ describe('jasmineUnderTest.pp', function() {
set.add('a'); set.add('a');
set.add('b'); set.add('b');
set.add('c'); set.add('c');
expect(jasmineUnderTest.pp(set)).toEqual("Set( 'a', 'b', ... )"); var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(set)).toEqual("Set( 'a', 'b', ... )");
} finally { } finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize; jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize;
} }
@@ -45,7 +49,8 @@ describe('jasmineUnderTest.pp', function() {
jasmine.getEnv().requireFunctioningMaps(); jasmine.getEnv().requireFunctioningMaps();
var map = new Map(); var map = new Map();
map.set(1, 2); map.set(1, 2);
expect(jasmineUnderTest.pp(map)).toEqual('Map( [ 1, 2 ] )'); var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(map)).toEqual('Map( [ 1, 2 ] )');
}); });
it('should truncate maps with more elements than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() { it('should truncate maps with more elements than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() {
@@ -58,9 +63,8 @@ describe('jasmineUnderTest.pp', function() {
map.set('a', 1); map.set('a', 1);
map.set('b', 2); map.set('b', 2);
map.set('c', 3); map.set('c', 3);
expect(jasmineUnderTest.pp(map)).toEqual( var pp = jasmineUnderTest.makePrettyPrinter();
"Map( [ 'a', 1 ], [ 'b', 2 ], ... )" expect(pp(map)).toEqual("Map( [ 'a', 1 ], [ 'b', 2 ], ... )");
);
} finally { } finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize; jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxSize;
} }
@@ -69,43 +73,44 @@ describe('jasmineUnderTest.pp', function() {
describe('stringify arrays', function() { describe('stringify arrays', function() {
it('should stringify arrays properly', function() { it('should stringify arrays properly', function() {
expect(jasmineUnderTest.pp([1, 2])).toEqual('[ 1, 2 ]'); var pp = jasmineUnderTest.makePrettyPrinter();
expect( expect(pp([1, 2])).toEqual('[ 1, 2 ]');
jasmineUnderTest.pp([1, 'foo', {}, jasmine.undefined, null]) expect(pp([1, 'foo', {}, jasmine.undefined, null])).toEqual(
).toEqual("[ 1, 'foo', Object({ }), undefined, null ]"); "[ 1, 'foo', Object({ }), undefined, null ]"
);
}); });
it('should truncate arrays that are longer than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() { it('should truncate arrays that are longer than jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH', function() {
var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH;
var array = [1, 2, 3]; var array = [1, 2, 3];
var pp = jasmineUnderTest.makePrettyPrinter();
try { try {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2; jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2;
expect(jasmineUnderTest.pp(array)).toEqual('[ 1, 2, ... ]'); expect(pp(array)).toEqual('[ 1, 2, ... ]');
} finally { } finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength; jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength;
} }
}); });
it('should stringify arrays with properties properly', function() { it('should stringify arrays with properties properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var arr = [1, 2]; var arr = [1, 2];
arr.foo = 'bar'; arr.foo = 'bar';
arr.baz = {}; arr.baz = {};
expect(jasmineUnderTest.pp(arr)).toEqual( expect(pp(arr)).toEqual("[ 1, 2, foo: 'bar', baz: Object({ }) ]");
"[ 1, 2, foo: 'bar', baz: Object({ }) ]"
);
}); });
it('should stringify empty arrays with properties properly', function() { it('should stringify empty arrays with properties properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var empty = []; var empty = [];
empty.foo = 'bar'; empty.foo = 'bar';
empty.baz = {}; empty.baz = {};
expect(jasmineUnderTest.pp(empty)).toEqual( expect(pp(empty)).toEqual("[ foo: 'bar', baz: Object({ }) ]");
"[ foo: 'bar', baz: Object({ }) ]"
);
}); });
it('should stringify long arrays with properties properly', function() { it('should stringify long arrays with properties properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH;
var long = [1, 2, 3]; var long = [1, 2, 3];
long.foo = 'bar'; long.foo = 'bar';
@@ -113,7 +118,7 @@ describe('jasmineUnderTest.pp', function() {
try { try {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2; jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2;
expect(jasmineUnderTest.pp(long)).toEqual( expect(pp(long)).toEqual(
"[ 1, 2, ..., foo: 'bar', baz: Object({ }) ]" "[ 1, 2, ..., foo: 'bar', baz: Object({ }) ]"
); );
} finally { } finally {
@@ -122,26 +127,25 @@ describe('jasmineUnderTest.pp', function() {
}); });
it('should indicate circular array references', function() { it('should indicate circular array references', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var array1 = [1, 2]; var array1 = [1, 2];
var array2 = [array1]; var array2 = [array1];
array1.push(array2); array1.push(array2);
expect(jasmineUnderTest.pp(array1)).toEqual( expect(pp(array1)).toEqual('[ 1, 2, [ <circular reference: Array> ] ]');
'[ 1, 2, [ <circular reference: Array> ] ]'
);
}); });
it('should not indicate circular references incorrectly', function() { it('should not indicate circular references incorrectly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var array = [[1]]; var array = [[1]];
expect(jasmineUnderTest.pp(array)).toEqual('[ [ 1 ] ]'); expect(pp(array)).toEqual('[ [ 1 ] ]');
}); });
}); });
it('should stringify objects properly', function() { it('should stringify objects properly', function() {
expect(jasmineUnderTest.pp({ foo: 'bar' })).toEqual( var pp = jasmineUnderTest.makePrettyPrinter();
"Object({ foo: 'bar' })" expect(pp({ foo: 'bar' })).toEqual("Object({ foo: 'bar' })");
);
expect( expect(
jasmineUnderTest.pp({ pp({
foo: 'bar', foo: 'bar',
baz: 3, baz: 3,
nullValue: null, nullValue: null,
@@ -150,24 +154,24 @@ describe('jasmineUnderTest.pp', function() {
).toEqual( ).toEqual(
"Object({ foo: 'bar', baz: 3, nullValue: null, undefinedValue: undefined })" "Object({ foo: 'bar', baz: 3, nullValue: null, undefinedValue: undefined })"
); );
expect(jasmineUnderTest.pp({ foo: function() {}, bar: [1, 2, 3] })).toEqual( expect(pp({ foo: function() {}, bar: [1, 2, 3] })).toEqual(
'Object({ foo: Function, bar: [ 1, 2, 3 ] })' 'Object({ foo: Function, bar: [ 1, 2, 3 ] })'
); );
}); });
it('should stringify objects that almost look like DOM nodes', function() { it('should stringify objects that almost look like DOM nodes', function() {
expect(jasmineUnderTest.pp({ nodeType: 1 })).toEqual( var pp = jasmineUnderTest.makePrettyPrinter();
'Object({ nodeType: 1 })' expect(pp({ nodeType: 1 })).toEqual('Object({ nodeType: 1 })');
);
}); });
it('should truncate objects with too many keys', function() { it('should truncate objects with too many keys', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH; var originalMaxLength = jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH;
var long = { a: 1, b: 2, c: 3 }; var long = { a: 1, b: 2, c: 3 };
try { try {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2; jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = 2;
expect(jasmineUnderTest.pp(long)).toEqual('Object({ a: 1, b: 2, ... })'); expect(pp(long)).toEqual('Object({ a: 1, b: 2, ... })');
} finally { } finally {
jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength; jasmineUnderTest.MAX_PRETTY_PRINT_ARRAY_LENGTH = originalMaxLength;
} }
@@ -185,12 +189,11 @@ describe('jasmineUnderTest.pp', function() {
} }
it('should truncate outputs that are too long', function() { it('should truncate outputs that are too long', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var big = [{ a: 1, b: 'a long string' }, {}]; var big = [{ a: 1, b: 'a long string' }, {}];
withMaxChars(34, function() { withMaxChars(34, function() {
expect(jasmineUnderTest.pp(big)).toEqual( expect(pp(big)).toEqual("[ Object({ a: 1, b: 'a long st ...");
"[ Object({ a: 1, b: 'a long st ..."
);
}); });
}); });
@@ -214,59 +217,55 @@ describe('jasmineUnderTest.pp', function() {
jasmineToString: jasmine jasmineToString: jasmine
.createSpy('d jasmineToString') .createSpy('d jasmineToString')
.and.returnValue('') .and.returnValue('')
}; },
pp = jasmineUnderTest.makePrettyPrinter();
withMaxChars(30, function() { withMaxChars(30, function() {
jasmineUnderTest.pp([{ a: a, b: b, c: c }, d]); pp([{ a: a, b: b, c: c }, d]);
expect(c.jasmineToString).not.toHaveBeenCalled(); expect(c.jasmineToString).not.toHaveBeenCalled();
expect(d.jasmineToString).not.toHaveBeenCalled(); expect(d.jasmineToString).not.toHaveBeenCalled();
}); });
}); });
it("should print 'null' as the constructor of an object with its own constructor property", function() { it("should print 'null' as the constructor of an object with its own constructor property", function() {
expect(jasmineUnderTest.pp({ constructor: function() {} })).toContain( var pp = jasmineUnderTest.makePrettyPrinter();
'null({' expect(pp({ constructor: function() {} })).toContain('null({');
); expect(pp({ constructor: 'foo' })).toContain('null({');
expect(jasmineUnderTest.pp({ constructor: 'foo' })).toContain('null({');
}); });
it('should not include inherited properties when stringifying an object', function() { it('should not include inherited properties when stringifying an object', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var SomeClass = function SomeClass() {}; var SomeClass = function SomeClass() {};
SomeClass.prototype.foo = 'inherited foo'; SomeClass.prototype.foo = 'inherited foo';
var instance = new SomeClass(); var instance = new SomeClass();
instance.bar = 'my own bar'; instance.bar = 'my own bar';
expect(jasmineUnderTest.pp(instance)).toEqual( expect(pp(instance)).toEqual("SomeClass({ bar: 'my own bar' })");
"SomeClass({ bar: 'my own bar' })"
);
}); });
it('should not recurse objects and arrays more deeply than jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH', function() { it('should not recurse objects and arrays more deeply than jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var originalMaxDepth = jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH; var originalMaxDepth = jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH;
var nestedObject = { level1: { level2: { level3: { level4: 'leaf' } } } }; var nestedObject = { level1: { level2: { level3: { level4: 'leaf' } } } };
var nestedArray = [1, [2, [3, [4, 'leaf']]]]; var nestedArray = [1, [2, [3, [4, 'leaf']]]];
try { try {
jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 2; jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 2;
expect(jasmineUnderTest.pp(nestedObject)).toEqual( expect(pp(nestedObject)).toEqual(
'Object({ level1: Object({ level2: Object }) })' 'Object({ level1: Object({ level2: Object }) })'
); );
expect(jasmineUnderTest.pp(nestedArray)).toEqual('[ 1, [ 2, Array ] ]'); expect(pp(nestedArray)).toEqual('[ 1, [ 2, Array ] ]');
jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 3; jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 3;
expect(jasmineUnderTest.pp(nestedObject)).toEqual( expect(pp(nestedObject)).toEqual(
'Object({ level1: Object({ level2: Object({ level3: Object }) }) })' 'Object({ level1: Object({ level2: Object({ level3: Object }) }) })'
); );
expect(jasmineUnderTest.pp(nestedArray)).toEqual( expect(pp(nestedArray)).toEqual('[ 1, [ 2, [ 3, Array ] ] ]');
'[ 1, [ 2, [ 3, Array ] ] ]'
);
jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 4; jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = 4;
expect(jasmineUnderTest.pp(nestedObject)).toEqual( expect(pp(nestedObject)).toEqual(
"Object({ level1: Object({ level2: Object({ level3: Object({ level4: 'leaf' }) }) }) })" "Object({ level1: Object({ level2: Object({ level3: Object({ level4: 'leaf' }) }) }) })"
); );
expect(jasmineUnderTest.pp(nestedArray)).toEqual( expect(pp(nestedArray)).toEqual("[ 1, [ 2, [ 3, [ 4, 'leaf' ] ] ] ]");
"[ 1, [ 2, [ 3, [ 4, 'leaf' ] ] ] ]"
);
} finally { } finally {
jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = originalMaxDepth; jasmineUnderTest.MAX_PRETTY_PRINT_DEPTH = originalMaxDepth;
} }
@@ -274,28 +273,32 @@ describe('jasmineUnderTest.pp', function() {
it('should stringify immutable circular objects', function() { it('should stringify immutable circular objects', function() {
if (Object.freeze) { if (Object.freeze) {
var pp = jasmineUnderTest.makePrettyPrinter();
var frozenObject = { foo: { bar: 'baz' } }; var frozenObject = { foo: { bar: 'baz' } };
frozenObject.circular = frozenObject; frozenObject.circular = frozenObject;
frozenObject = Object.freeze(frozenObject); frozenObject = Object.freeze(frozenObject);
expect(jasmineUnderTest.pp(frozenObject)).toEqual( expect(pp(frozenObject)).toEqual(
"Object({ foo: Object({ bar: 'baz' }), circular: <circular reference: Object> })" "Object({ foo: Object({ bar: 'baz' }), circular: <circular reference: Object> })"
); );
} }
}); });
it('should stringify RegExp objects properly', function() { it('should stringify RegExp objects properly', function() {
expect(jasmineUnderTest.pp(/x|y|z/)).toEqual('/x|y|z/'); var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(/x|y|z/)).toEqual('/x|y|z/');
}); });
it('should indicate circular object references', function() { it('should indicate circular object references', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var sampleValue = { foo: 'hello' }; var sampleValue = { foo: 'hello' };
sampleValue.nested = sampleValue; sampleValue.nested = sampleValue;
expect(jasmineUnderTest.pp(sampleValue)).toEqual( expect(pp(sampleValue)).toEqual(
"Object({ foo: 'hello', nested: <circular reference: Object> })" "Object({ foo: 'hello', nested: <circular reference: Object> })"
); );
}); });
it('should indicate getters on objects as such', function() { it('should indicate getters on objects as such', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var sampleValue = { id: 1 }; var sampleValue = { id: 1 };
if (sampleValue.__defineGetter__) { if (sampleValue.__defineGetter__) {
//not supported in IE! //not supported in IE!
@@ -304,34 +307,38 @@ describe('jasmineUnderTest.pp', function() {
}); });
} }
if (sampleValue.__defineGetter__) { if (sampleValue.__defineGetter__) {
expect(jasmineUnderTest.pp(sampleValue)).toEqual( expect(pp(sampleValue)).toEqual(
'Object({ id: 1, calculatedValue: <getter> })' 'Object({ id: 1, calculatedValue: <getter> })'
); );
} else { } else {
expect(jasmineUnderTest.pp(sampleValue)).toEqual('Object({ id: 1 })'); expect(pp(sampleValue)).toEqual('Object({ id: 1 })');
} }
}); });
it('should not do HTML escaping of strings', function() { it('should not do HTML escaping of strings', function() {
expect(jasmineUnderTest.pp('some <b>html string</b> &', false)).toEqual( var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp('some <b>html string</b> &', false)).toEqual(
"'some <b>html string</b> &'" "'some <b>html string</b> &'"
); );
}); });
it('should abbreviate the global (usually window) object', function() { it('should abbreviate the global (usually window) object', function() {
expect(jasmineUnderTest.pp(jasmine.getGlobal())).toEqual('<global>'); var pp = jasmineUnderTest.makePrettyPrinter();
expect(pp(jasmine.getGlobal())).toEqual('<global>');
}); });
it('should stringify Date objects properly', function() { it('should stringify Date objects properly', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var now = new Date(); var now = new Date();
expect(jasmineUnderTest.pp(now)).toEqual('Date(' + now.toString() + ')'); expect(pp(now)).toEqual('Date(' + now.toString() + ')');
}); });
it('should stringify spy objects properly', function() { it('should stringify spy objects properly', function() {
var TestObject = { var TestObject = {
someFunction: function() {} someFunction: function() {}
}, },
env = new jasmineUnderTest.Env(); env = new jasmineUnderTest.Env(),
pp = jasmineUnderTest.makePrettyPrinter();
var spyRegistry = new jasmineUnderTest.SpyRegistry({ var spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
@@ -343,20 +350,17 @@ describe('jasmineUnderTest.pp', function() {
}); });
spyRegistry.spyOn(TestObject, 'someFunction'); spyRegistry.spyOn(TestObject, 'someFunction');
expect(jasmineUnderTest.pp(TestObject.someFunction)).toEqual( expect(pp(TestObject.someFunction)).toEqual('spy on someFunction');
'spy on someFunction'
);
expect(jasmineUnderTest.pp(env.createSpy('something'))).toEqual( expect(pp(env.createSpy('something'))).toEqual('spy on something');
'spy on something'
);
}); });
it('should stringify spyOn toString properly', function() { it('should stringify spyOn toString properly', function() {
var TestObject = { var TestObject = {
someFunction: function() {} someFunction: function() {}
}, },
env = new jasmineUnderTest.Env(); env = new jasmineUnderTest.Env(),
pp = jasmineUnderTest.makePrettyPrinter();
var spyRegistry = new jasmineUnderTest.SpyRegistry({ var spyRegistry = new jasmineUnderTest.SpyRegistry({
currentSpies: function() { currentSpies: function() {
@@ -370,29 +374,29 @@ describe('jasmineUnderTest.pp', function() {
spyRegistry.spyOn(TestObject, 'toString'); spyRegistry.spyOn(TestObject, 'toString');
var testSpyObj = env.createSpyObj('TheClassName', ['toString']); var testSpyObj = env.createSpyObj('TheClassName', ['toString']);
expect(jasmineUnderTest.pp(testSpyObj)).toEqual( expect(pp(testSpyObj)).toEqual('spy on TheClassName.toString');
'spy on TheClassName.toString'
);
}); });
it('should stringify objects that implement jasmineToString', function() { it('should stringify objects that implement jasmineToString', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var obj = { var obj = {
jasmineToString: function() { jasmineToString: function() {
return 'strung'; return 'strung';
} }
}; };
expect(jasmineUnderTest.pp(obj)).toEqual('strung'); expect(pp(obj)).toEqual('strung');
}); });
it('should stringify objects that implement custom toString', function() { it('should stringify objects that implement custom toString', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var obj = { var obj = {
toString: function() { toString: function() {
return 'my toString'; return 'my toString';
} }
}; };
expect(jasmineUnderTest.pp(obj)).toEqual('my toString'); expect(pp(obj)).toEqual('my toString');
// Simulate object from another global context (e.g. an iframe or Web Worker) that does not actually have a custom // Simulate object from another global context (e.g. an iframe or Web Worker) that does not actually have a custom
// toString despite obj.toString !== Object.prototype.toString // toString despite obj.toString !== Object.prototype.toString
@@ -403,20 +407,22 @@ describe('jasmineUnderTest.pp', function() {
} }
}; };
expect(jasmineUnderTest.pp(objFromOtherContext)).toEqual( expect(pp(objFromOtherContext)).toEqual(
"Object({ foo: 'bar', toString: Function })" "Object({ foo: 'bar', toString: Function })"
); );
}); });
it("should stringify objects have have a toString that isn't a function", function() { it("should stringify objects have have a toString that isn't a function", function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var obj = { var obj = {
toString: 'foo' toString: 'foo'
}; };
expect(jasmineUnderTest.pp(obj)).toEqual("Object({ toString: 'foo' })"); expect(pp(obj)).toEqual("Object({ toString: 'foo' })");
}); });
it('should stringify objects from anonymous constructors with custom toString', function() { it('should stringify objects from anonymous constructors with custom toString', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var MyAnonymousConstructor = (function() { var MyAnonymousConstructor = (function() {
return function() {}; return function() {};
})(); })();
@@ -426,17 +432,19 @@ describe('jasmineUnderTest.pp', function() {
var a = new MyAnonymousConstructor(); var a = new MyAnonymousConstructor();
expect(jasmineUnderTest.pp(a)).toEqual('<anonymous>({ })'); expect(pp(a)).toEqual('<anonymous>({ })');
}); });
it('should handle objects with null prototype', function() { it('should handle objects with null prototype', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var obj = Object.create(null); var obj = Object.create(null);
obj.foo = 'bar'; obj.foo = 'bar';
expect(jasmineUnderTest.pp(obj)).toEqual("null({ foo: 'bar' })"); expect(pp(obj)).toEqual("null({ foo: 'bar' })");
}); });
it('should gracefully handle objects with invalid toString implementations', function() { it('should gracefully handle objects with invalid toString implementations', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var obj = { var obj = {
foo: { foo: {
toString: function() { toString: function() {
@@ -466,7 +474,7 @@ describe('jasmineUnderTest.pp', function() {
} }
}; };
expect(jasmineUnderTest.pp(obj)).toEqual( expect(pp(obj)).toEqual(
'Object({ foo: [object Number], bar: [object Object], baz: 3, qux: Error: bar, baddy: has-invalid-toString-method })' 'Object({ foo: [object Number], bar: [object Object], baz: 3, qux: Error: bar, baddy: has-invalid-toString-method })'
); );
}); });
@@ -2,7 +2,7 @@ describe('#toBeRejectedWithError', function () {
it('passes when Error type matches', function () { it('passes when Error type matches', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new TypeError('foo')); actual = Promise.reject(new TypeError('foo'));
@@ -17,7 +17,7 @@ describe('#toBeRejectedWithError', function () {
it('passes when Error type and message matches', function () { it('passes when Error type and message matches', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new TypeError('foo')); actual = Promise.reject(new TypeError('foo'));
@@ -32,7 +32,7 @@ describe('#toBeRejectedWithError', function () {
it('passes when Error matches and is exactly Error', function() { it('passes when Error matches and is exactly Error', function() {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error()); actual = Promise.reject(new Error());
@@ -48,7 +48,7 @@ describe('#toBeRejectedWithError', function () {
it('passes when Error message matches a string', function () { it('passes when Error message matches a string', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error('foo')); actual = Promise.reject(new Error('foo'));
@@ -63,7 +63,7 @@ describe('#toBeRejectedWithError', function () {
it('passes when Error message matches a RegExp', function () { it('passes when Error message matches a RegExp', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error('foo')); actual = Promise.reject(new Error('foo'));
@@ -78,7 +78,7 @@ describe('#toBeRejectedWithError', function () {
it('passes when Error message is empty', function () { it('passes when Error message is empty', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error()); actual = Promise.reject(new Error());
@@ -93,7 +93,7 @@ describe('#toBeRejectedWithError', function () {
it('passes when no arguments', function () { it('passes when no arguments', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error()); actual = Promise.reject(new Error());
@@ -108,7 +108,7 @@ describe('#toBeRejectedWithError', function () {
it('fails when resolved', function () { it('fails when resolved', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.resolve(new Error('foo')); actual = Promise.resolve(new Error('foo'));
@@ -123,7 +123,7 @@ describe('#toBeRejectedWithError', function () {
it('fails when rejected with non Error type', function () { it('fails when rejected with non Error type', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject('foo'); actual = Promise.reject('foo');
@@ -138,7 +138,7 @@ describe('#toBeRejectedWithError', function () {
it('fails when Error type mismatches', function () { it('fails when Error type mismatches', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error('foo')); actual = Promise.reject(new Error('foo'));
@@ -153,7 +153,7 @@ describe('#toBeRejectedWithError', function () {
it('fails when Error message mismatches', function () { it('fails when Error message mismatches', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = Promise.reject(new Error('foo')); actual = Promise.reject(new Error('foo'));
@@ -166,7 +166,7 @@ describe('#toBeRejectedWithError', function () {
}); });
it('fails if actual is not a promise', function() { it('fails if actual is not a promise', function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWithError(matchersUtil),
actual = 'not a promise'; actual = 'not a promise';
@@ -26,7 +26,7 @@ describe('#toBeRejectedWith', function () {
it('should fail if the promise is rejected with a different value', function () { it('should fail if the promise is rejected with a different value', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.reject('A Bad Apple'); actual = Promise.reject('A Bad Apple');
@@ -41,7 +41,7 @@ describe('#toBeRejectedWith', function () {
it('should build its error correctly when negated', function () { it('should build its error correctly when negated', function () {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = Promise.reject(true); actual = Promise.reject(true);
@@ -67,7 +67,7 @@ describe('#toBeRejectedWith', function () {
}); });
it('fails if actual is not a promise', function() { it('fails if actual is not a promise', function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(matchersUtil),
actual = 'not a promise'; actual = 'not a promise';
@@ -14,7 +14,7 @@ describe('#toBeResolvedTo', function() {
it('fails if the promise is rejected', function() { it('fails if the promise is rejected', function() {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.reject('AsyncExpectationSpec error'); actual = Promise.reject('AsyncExpectationSpec error');
@@ -29,7 +29,7 @@ describe('#toBeResolvedTo', function() {
it('fails if the promise is resolved to a different value', function() { it('fails if the promise is resolved to a different value', function() {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.resolve({foo: 17}); actual = Promise.resolve({foo: 17});
@@ -44,7 +44,7 @@ describe('#toBeResolvedTo', function() {
it('builds its message correctly when negated', function() { it('builds its message correctly when negated', function() {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: new jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.resolve(true); actual = Promise.resolve(true);
@@ -60,7 +60,10 @@ describe('#toBeResolvedTo', function() {
jasmine.getEnv().requirePromises(); jasmine.getEnv().requirePromises();
var customEqualityTesters = [function() { return true; }], var customEqualityTesters = [function() { return true; }],
matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: customEqualityTesters}), matchersUtil = new jasmineUnderTest.MatchersUtil({
customTesters: customEqualityTesters,
pp: jasmineUnderTest.makePrettyPrinter()
}),
matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = Promise.resolve('actual'); actual = Promise.resolve('actual');
@@ -70,7 +73,7 @@ describe('#toBeResolvedTo', function() {
}); });
it('fails if actual is not a promise', function() { it('fails if actual is not a promise', function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil(), var matchersUtil = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil), matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(matchersUtil),
actual = 'not a promise'; actual = 'not a promise';
+31 -10
View File
@@ -1,4 +1,11 @@
describe("matchersUtil", function() { describe("matchersUtil", function() {
it("exposes the injected pretty-printer as .pp", function() {
var pp = function() {},
matchersUtil = new jasmineUnderTest.MatchersUtil({pp: pp});
expect(matchersUtil.pp).toBe(pp);
});
describe("equals", function() { describe("equals", function() {
it("passes for literals that are triple-equal", function() { it("passes for literals that are triple-equal", function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil(); var matchersUtil = new jasmineUnderTest.MatchersUtil();
@@ -76,7 +83,7 @@ describe("matchersUtil", function() {
}); });
it("fails for Arrays that have different lengths", function() { it("fails for Arrays that have different lengths", function() {
var matchersUtil = new jasmineUnderTest.MatchersUtil(); matchersUtil = new jasmineUnderTest.MatchersUtil();
expect(matchersUtil.equals([1, 2], [1, 2, 3])).toBe(false); expect(matchersUtil.equals([1, 2], [1, 2, 3])).toBe(false);
}); });
@@ -392,7 +399,7 @@ describe("matchersUtil", function() {
it("passes when a custom equality matcher passed to the constructor returns true", function() { it("passes when a custom equality matcher passed to the constructor returns true", function() {
var tester = function(a, b) { return true; }, var tester = function(a, b) { return true; },
matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester]}); matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester], pp: function() {}});
expect(matchersUtil.equals(1, 2)).toBe(true); expect(matchersUtil.equals(1, 2)).toBe(true);
}); });
@@ -416,7 +423,7 @@ describe("matchersUtil", function() {
var tester = function(a, b) { return jasmine.undefined; }; var tester = function(a, b) { return jasmine.undefined; };
it("passes for two empty Objects", function () { it("passes for two empty Objects", function () {
var matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester]}); var matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester], pp: function() {}});
expect(matchersUtil.equals({}, {})).toBe(true); expect(matchersUtil.equals({}, {})).toBe(true);
}); });
}); });
@@ -431,7 +438,7 @@ describe("matchersUtil", function() {
it("fails for equivalents when a custom equality matcher passed to the constructor returns false", function() { it("fails for equivalents when a custom equality matcher passed to the constructor returns false", function() {
var tester = function(a, b) { return false; }, var tester = function(a, b) { return false; },
matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester]}); matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [tester], pp: function() {}});
expect(matchersUtil.equals(1, 1)).toBe(false); expect(matchersUtil.equals(1, 1)).toBe(false);
}); });
@@ -449,7 +456,7 @@ describe("matchersUtil", function() {
it("passes for an asymmetric equality tester that returns true when a custom equality tester passed to the constructor return false", function() { it("passes for an asymmetric equality tester that returns true when a custom equality tester passed to the constructor return false", function() {
var asymmetricTester = { asymmetricMatch: function(other) { return true; } }, var asymmetricTester = { asymmetricMatch: function(other) { return true; } },
symmetricTester = function(a, b) { return false; }, symmetricTester = function(a, b) { return false; },
matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [symmetricTester()]}); matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [symmetricTester()], pp: function() {}});
expect(matchersUtil.equals(asymmetricTester, true)).toBe(true); expect(matchersUtil.equals(asymmetricTester, true)).toBe(true);
expect(matchersUtil.equals(true, asymmetricTester)).toBe(true); expect(matchersUtil.equals(true, asymmetricTester)).toBe(true);
@@ -475,7 +482,7 @@ describe("matchersUtil", function() {
it("is both a matchersUtil and the custom equality testers passed to the constructor", function() { it("is both a matchersUtil and the custom equality testers passed to the constructor", function() {
var asymmetricTester = jasmine.createSpyObj('tester', ['asymmetricMatch']), var asymmetricTester = jasmine.createSpyObj('tester', ['asymmetricMatch']),
symmetricTester = function() { } , symmetricTester = function() { } ,
matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [symmetricTester]}), matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [symmetricTester], pp: function() {}}),
shim; shim;
matchersUtil.equals(true, asymmetricTester); matchersUtil.equals(true, asymmetricTester);
@@ -783,7 +790,7 @@ describe("matchersUtil", function() {
it("uses custom equality testers if passed to the constructor and actual is an Array", function() { it("uses custom equality testers if passed to the constructor and actual is an Array", function() {
var customTester = function(a, b) {return true;}, var customTester = function(a, b) {return true;},
matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [customTester]}); matchersUtil = new jasmineUnderTest.MatchersUtil({customTesters: [customTester], pp: function() {}});
expect(matchersUtil.contains([1, 2], 3)).toBe(true); expect(matchersUtil.contains([1, 2], 3)).toBe(true);
}); });
@@ -838,7 +845,8 @@ describe("matchersUtil", function() {
it("builds an English sentence for a failure case", function() { it("builds an English sentence for a failure case", function() {
var actual = "foo", var actual = "foo",
name = "toBar", name = "toBar",
matchersUtil = new jasmineUnderTest.MatchersUtil(), pp = jasmineUnderTest.makePrettyPrinter(),
matchersUtil = new jasmineUnderTest.MatchersUtil({pp: pp}),
message = matchersUtil.buildFailureMessage(name, false, actual); message = matchersUtil.buildFailureMessage(name, false, actual);
expect(message).toEqual("Expected 'foo' to bar."); expect(message).toEqual("Expected 'foo' to bar.");
@@ -848,7 +856,8 @@ describe("matchersUtil", function() {
var actual = "foo", var actual = "foo",
name = "toBar", name = "toBar",
isNot = true, isNot = true,
matchersUtil = new jasmineUnderTest.MatchersUtil(), pp = jasmineUnderTest.makePrettyPrinter(),
matchersUtil = new jasmineUnderTest.MatchersUtil({pp: pp}),
message = message = matchersUtil.buildFailureMessage(name, isNot, actual); message = message = matchersUtil.buildFailureMessage(name, isNot, actual);
expect(message).toEqual("Expected 'foo' not to bar."); expect(message).toEqual("Expected 'foo' not to bar.");
@@ -857,10 +866,22 @@ describe("matchersUtil", function() {
it("builds an English sentence for an arbitrary array of expected arguments", function() { it("builds an English sentence for an arbitrary array of expected arguments", function() {
var actual = "foo", var actual = "foo",
name = "toBar", name = "toBar",
matchersUtil = new jasmineUnderTest.MatchersUtil(), pp = jasmineUnderTest.makePrettyPrinter(),
matchersUtil = new jasmineUnderTest.MatchersUtil({pp: pp}),
message = matchersUtil.buildFailureMessage(name, false, actual, "quux", "corge"); message = matchersUtil.buildFailureMessage(name, false, actual, "quux", "corge");
expect(message).toEqual("Expected 'foo' to bar 'quux', 'corge'."); expect(message).toEqual("Expected 'foo' to bar 'quux', 'corge'.");
}); });
it("uses the injected pretty-printer to format the expected", function() {
var actual = "foo",
name = "toBar",
isNot = false,
pp = function(value) { return '<' + value + '>'; },
matchersUtil = new jasmineUnderTest.MatchersUtil({pp: pp}),
message = message = matchersUtil.buildFailureMessage(name, isNot, actual);
expect(message).toEqual("Expected <foo> to bar.");
});
}); });
}); });
+9 -3
View File
@@ -10,7 +10,9 @@ describe('toBeInstanceOf', function() {
}); });
it('passes for NaN', function() { it('passes for NaN', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf(); var matcher = jasmineUnderTest.matchers.toBeInstanceOf({
pp: jasmineUnderTest.makePrettyPrinter()
});
var result = matcher.compare(NaN, Number); var result = matcher.compare(NaN, Number);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -156,7 +158,9 @@ describe('toBeInstanceOf', function() {
it('passes for objects with no constructor', function() { it('passes for objects with no constructor', function() {
var object = Object.create(null); var object = Object.create(null);
var matcher = jasmineUnderTest.matchers.toBeInstanceOf(); var matcher = jasmineUnderTest.matchers.toBeInstanceOf({
pp: jasmineUnderTest.makePrettyPrinter()
});
var result = matcher.compare(object, Object); var result = matcher.compare(object, Object);
expect(result).toEqual({ expect(result).toEqual({
pass: true, pass: true,
@@ -219,7 +223,9 @@ describe('toBeInstanceOf', function() {
}); });
it('raises an error if missing an expected value', function() { it('raises an error if missing an expected value', function() {
var matcher = jasmineUnderTest.matchers.toBeInstanceOf(); var matcher = jasmineUnderTest.matchers.toBeInstanceOf({
pp: jasmineUnderTest.makePrettyPrinter()
});
expect(function() { expect(function() {
matcher.compare({}, undefined); matcher.compare({}, undefined);
}).toThrowError('<toBeInstanceOf> : Expected value is not a constructor function\n' + }).toThrowError('<toBeInstanceOf> : Expected value is not a constructor function\n' +
+3 -1
View File
@@ -29,7 +29,9 @@ describe("toBeNaN", function() {
}); });
it("has a custom message on failure", function() { it("has a custom message on failure", function() {
var matcher = jasmineUnderTest.matchers.toBeNaN(), var matcher = jasmineUnderTest.matchers.toBeNaN({
pp: jasmineUnderTest.makePrettyPrinter()
}),
result = matcher.compare(0); result = matcher.compare(0);
expect(result.message()).toEqual("Expected 0 to be NaN."); expect(result.message()).toEqual("Expected 0 to be NaN.");
@@ -14,7 +14,9 @@ describe("toBeNegativeInfinity", function() {
}); });
it("has a custom message on failure", function() { it("has a custom message on failure", function() {
var matcher = jasmineUnderTest.matchers.toBeNegativeInfinity(), var matcher = jasmineUnderTest.matchers.toBeNegativeInfinity({
pp: jasmineUnderTest.makePrettyPrinter()
}),
result = matcher.compare(0); result = matcher.compare(0);
expect(result.message()).toEqual("Expected 0 to be -Infinity.") expect(result.message()).toEqual("Expected 0 to be -Infinity.")
@@ -14,7 +14,9 @@ describe("toBePositiveInfinity", function() {
}); });
it("has a custom message on failure", function() { it("has a custom message on failure", function() {
var matcher = jasmineUnderTest.matchers.toBePositiveInfinity(), var matcher = jasmineUnderTest.matchers.toBePositiveInfinity({
pp: jasmineUnderTest.makePrettyPrinter()
}),
result = matcher.compare(0); result = matcher.compare(0);
expect(result.message()).toEqual("Expected 0 to be Infinity.") expect(result.message()).toEqual("Expected 0 to be Infinity.")
+4 -4
View File
@@ -9,7 +9,7 @@ describe("toBe", function() {
}); });
it("passes with a custom message when expected is an array", function() { it("passes with a custom message when expected is an array", function() {
var util = new jasmineUnderTest.MatchersUtil(), var util = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.matchers.toBe(util), matcher = jasmineUnderTest.matchers.toBe(util),
result, result,
array = [1]; array = [1];
@@ -20,7 +20,7 @@ describe("toBe", function() {
}); });
it("passes with a custom message when expected is an object", function() { it("passes with a custom message when expected is an object", function() {
var util = new jasmineUnderTest.MatchersUtil(), var util = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.matchers.toBe(util), matcher = jasmineUnderTest.matchers.toBe(util),
result, result,
obj = {foo: "bar"}; obj = {foo: "bar"};
@@ -41,7 +41,7 @@ describe("toBe", function() {
}); });
it("fails with a custom message when expected is an array", function() { it("fails with a custom message when expected is an array", function() {
var util = new jasmineUnderTest.MatchersUtil(), var util = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.matchers.toBe(util), matcher = jasmineUnderTest.matchers.toBe(util),
result; result;
@@ -51,7 +51,7 @@ describe("toBe", function() {
}); });
it("fails with a custom message when expected is an object", function() { it("fails with a custom message when expected is an object", function() {
var util = new jasmineUnderTest.MatchersUtil(), var util = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.matchers.toBe(util), matcher = jasmineUnderTest.matchers.toBe(util),
result; result;
+3 -3
View File
@@ -2,7 +2,9 @@ describe("toEqual", function() {
"use strict"; "use strict";
function compareEquals(actual, expected) { function compareEquals(actual, expected) {
var util = new jasmineUnderTest.MatchersUtil(), var util = new jasmineUnderTest.MatchersUtil({
pp: jasmineUnderTest.makePrettyPrinter()
}),
matcher = jasmineUnderTest.matchers.toEqual(util); matcher = jasmineUnderTest.matchers.toEqual(util);
var result = matcher.compare(actual, expected); var result = matcher.compare(actual, expected);
@@ -103,8 +105,6 @@ describe("toEqual", function() {
" g: 3\n" + " g: 3\n" +
"Expected $.x not to have properties\n" + "Expected $.x not to have properties\n" +
" f: 4"; " f: 4";
expect(compareEquals(actual, expected).message).toEqual(message);
}); });
it("reports extra and missing properties of the root-level object", function() { it("reports extra and missing properties of the root-level object", function() {
@@ -1,6 +1,8 @@
describe("toHaveBeenCalledBefore", function() { describe("toHaveBeenCalledBefore", function() {
it("throws an exception when the actual is not a spy", function() { it("throws an exception when the actual is not a spy", function() {
var matcher = jasmineUnderTest.matchers.toHaveBeenCalledBefore(), var matcher = jasmineUnderTest.matchers.toHaveBeenCalledBefore({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() {}, fn = function() {},
secondSpy = new jasmineUnderTest.Env().createSpy('second spy'); secondSpy = new jasmineUnderTest.Env().createSpy('second spy');
@@ -8,7 +10,9 @@ describe("toHaveBeenCalledBefore", function() {
}); });
it("throws an exception when the expected is not a spy", function() { it("throws an exception when the expected is not a spy", function() {
var matcher = jasmineUnderTest.matchers.toHaveBeenCalledBefore(), var matcher = jasmineUnderTest.matchers.toHaveBeenCalledBefore({
pp: jasmineUnderTest.makePrettyPrinter()
}),
firstSpy = new jasmineUnderTest.Env().createSpy('first spy'), firstSpy = new jasmineUnderTest.Env().createSpy('first spy'),
fn = function() {}; fn = function() {};
+3 -1
View File
@@ -21,7 +21,9 @@ describe("toHaveBeenCalled", function() {
}); });
it("throws an exception when the actual is not a spy", function() { it("throws an exception when the actual is not a spy", function() {
var matcher = jasmineUnderTest.matchers.toHaveBeenCalled(), var matcher = jasmineUnderTest.matchers.toHaveBeenCalled({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() {}; fn = function() {};
expect(function() { matcher.compare(fn) }).toThrowError(Error, /Expected a spy, but got Function./); expect(function() { matcher.compare(fn) }).toThrowError(Error, /Expected a spy, but got Function./);
@@ -49,7 +49,9 @@ describe("toHaveBeenCalledTimes", function() {
}); });
it("throws an exception when the actual is not a spy", function() { it("throws an exception when the actual is not a spy", function() {
var matcher = jasmineUnderTest.matchers.toHaveBeenCalledTimes(), var matcher = jasmineUnderTest.matchers.toHaveBeenCalledTimes({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() {}; fn = function() {};
expect(function() { expect(function() {
+10 -5
View File
@@ -2,7 +2,8 @@ describe("toHaveBeenCalledWith", function() {
it("passes when the actual was called with matching parameters", function() { it("passes when the actual was called with matching parameters", function() {
var util = { var util = {
contains: jasmine.createSpy('delegated-contains').and.returnValue(true) contains: jasmine.createSpy('delegated-contains').and.returnValue(true),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(util), matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(util),
calledSpy = new jasmineUnderTest.Env().createSpy('called-spy'), calledSpy = new jasmineUnderTest.Env().createSpy('called-spy'),
@@ -29,7 +30,8 @@ describe("toHaveBeenCalledWith", function() {
it("fails when the actual was not called", function() { it("fails when the actual was not called", function() {
var util = { var util = {
contains: jasmine.createSpy('delegated-contains').and.returnValue(false) contains: jasmine.createSpy('delegated-contains').and.returnValue(false),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(util), matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(util),
uncalledSpy = new jasmineUnderTest.Env().createSpy('uncalled spy'), uncalledSpy = new jasmineUnderTest.Env().createSpy('uncalled spy'),
@@ -41,7 +43,7 @@ describe("toHaveBeenCalledWith", function() {
}); });
it("fails when the actual was called with different parameters", function() { it("fails when the actual was called with different parameters", function() {
var util = new jasmineUnderTest.MatchersUtil(), var util = new jasmineUnderTest.MatchersUtil({pp: jasmineUnderTest.makePrettyPrinter()}),
matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(util), matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(util),
calledSpy = new jasmineUnderTest.Env().createSpy('called spy'), calledSpy = new jasmineUnderTest.Env().createSpy('called spy'),
result; result;
@@ -71,8 +73,11 @@ describe("toHaveBeenCalledWith", function() {
}); });
it("throws an exception when the actual is not a spy", function() { it("throws an exception when the actual is not a spy", function() {
var matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith(), var matcher = jasmineUnderTest.matchers.toHaveBeenCalledWith({
fn = function() {}; pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function () {
};
expect(function() { matcher.compare(fn) }).toThrowError(/Expected a spy, but got Function./); expect(function() { matcher.compare(fn) }).toThrowError(/Expected a spy, but got Function./);
}); });
+3 -1
View File
@@ -27,7 +27,9 @@ describe('toHaveClass', function() {
}); });
it('throws an exception when actual is not a DOM element', function() { it('throws an exception when actual is not a DOM element', function() {
var matcher = jasmineUnderTest.matchers.toHaveClass(); var matcher = jasmineUnderTest.matchers.toHaveClass({
pp: jasmineUnderTest.makePrettyPrinter()
});
expect(function() { expect(function() {
matcher.compare('x', 'foo'); matcher.compare('x', 'foo');
+33 -16
View File
@@ -54,7 +54,9 @@ describe("toThrowError", function() {
}); });
it("fails if thrown is not an instanceof Error", function() { it("fails if thrown is not an instanceof Error", function() {
var matcher = jasmineUnderTest.matchers.toThrowError(), var matcher = jasmineUnderTest.matchers.toThrowError({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() { fn = function() {
throw 4; throw 4;
}, },
@@ -103,7 +105,9 @@ describe("toThrowError", function() {
}); });
it("fails with the correct message if thrown is a falsy value", function() { it("fails with the correct message if thrown is a falsy value", function() {
var matcher = jasmineUnderTest.matchers.toThrowError(), var matcher = jasmineUnderTest.matchers.toThrowError({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() { fn = function() {
throw undefined; throw undefined;
}, },
@@ -128,7 +132,9 @@ describe("toThrowError", function() {
}); });
it("passes if thrown is an Error and the expected is the same message", function() { it("passes if thrown is an Error and the expected is the same message", function() {
var matcher = jasmineUnderTest.matchers.toThrowError(), var matcher = jasmineUnderTest.matchers.toThrowError({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() { fn = function() {
throw new Error("foo"); throw new Error("foo");
}, },
@@ -141,7 +147,9 @@ describe("toThrowError", function() {
}); });
it("fails if thrown is an Error and the expected is not the same message", function() { it("fails if thrown is an Error and the expected is not the same message", function() {
var matcher = jasmineUnderTest.matchers.toThrowError(), var matcher = jasmineUnderTest.matchers.toThrowError({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() { fn = function() {
throw new Error("foo"); throw new Error("foo");
}, },
@@ -154,7 +162,9 @@ describe("toThrowError", function() {
}); });
it("passes if thrown is an Error and the expected is a RegExp that matches the message", function() { it("passes if thrown is an Error and the expected is a RegExp that matches the message", function() {
var matcher = jasmineUnderTest.matchers.toThrowError(), var matcher = jasmineUnderTest.matchers.toThrowError({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() { fn = function() {
throw new Error("a long message"); throw new Error("a long message");
}, },
@@ -167,7 +177,9 @@ describe("toThrowError", function() {
}); });
it("fails if thrown is an Error and the expected is a RegExp that does not match the message", function() { it("fails if thrown is an Error and the expected is a RegExp that does not match the message", function() {
var matcher = jasmineUnderTest.matchers.toThrowError(), var matcher = jasmineUnderTest.matchers.toThrowError({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() { fn = function() {
throw new Error("a long message"); throw new Error("a long message");
}, },
@@ -232,9 +244,10 @@ describe("toThrowError", function() {
it("passes if thrown is a type of Error and it is equal to the expected Error and message", function() { it("passes if thrown is a type of Error and it is equal to the expected Error and message", function() {
var util = { var util = {
equals: jasmine.createSpy('delegated-equal').and.returnValue(true) equals: jasmine.createSpy('delegated-equal').and.returnValue(true),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toThrowError(), matcher = jasmineUnderTest.matchers.toThrowError(util),
fn = function() { fn = function() {
throw new TypeError("foo"); throw new TypeError("foo");
}, },
@@ -248,9 +261,10 @@ describe("toThrowError", function() {
it("passes if thrown is a custom error that takes arguments and it is equal to the expected custom error and message", function() { it("passes if thrown is a custom error that takes arguments and it is equal to the expected custom error and message", function() {
var util = { var util = {
equals: jasmine.createSpy('delegated-equal').and.returnValue(true) equals: jasmine.createSpy('delegated-equal').and.returnValue(true),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toThrowError(), matcher = jasmineUnderTest.matchers.toThrowError(util),
CustomError = function CustomError(arg) { this.message = arg.message }, CustomError = function CustomError(arg) { this.message = arg.message },
fn = function() { fn = function() {
throw new CustomError({message: "foo"}); throw new CustomError({message: "foo"});
@@ -267,9 +281,10 @@ describe("toThrowError", function() {
it("fails if thrown is a type of Error and the expected is a different Error", function() { it("fails if thrown is a type of Error and the expected is a different Error", function() {
var util = { var util = {
equals: jasmine.createSpy('delegated-equal').and.returnValue(false) equals: jasmine.createSpy('delegated-equal').and.returnValue(false),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toThrowError(), matcher = jasmineUnderTest.matchers.toThrowError(util),
fn = function() { fn = function() {
throw new TypeError("foo"); throw new TypeError("foo");
}, },
@@ -283,9 +298,10 @@ describe("toThrowError", function() {
it("passes if thrown is a type of Error and has the same type as the expected Error and the message matches the expected message", function() { it("passes if thrown is a type of Error and has the same type as the expected Error and the message matches the expected message", function() {
var util = { var util = {
equals: jasmine.createSpy('delegated-equal').and.returnValue(true) equals: jasmine.createSpy('delegated-equal').and.returnValue(true),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toThrowError(), matcher = jasmineUnderTest.matchers.toThrowError(util),
fn = function() { fn = function() {
throw new TypeError("foo"); throw new TypeError("foo");
}, },
@@ -299,9 +315,10 @@ describe("toThrowError", function() {
it("fails if thrown is a type of Error and the expected is a different Error", function() { it("fails if thrown is a type of Error and the expected is a different Error", function() {
var util = { var util = {
equals: jasmine.createSpy('delegated-equal').and.returnValue(false) equals: jasmine.createSpy('delegated-equal').and.returnValue(false),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toThrowError(), matcher = jasmineUnderTest.matchers.toThrowError(util),
fn = function() { fn = function() {
throw new TypeError("foo"); throw new TypeError("foo");
}, },
+7 -3
View File
@@ -32,7 +32,9 @@ describe("toThrowMatching", function() {
}); });
it("fails with the correct message if thrown is a falsy value", function() { it("fails with the correct message if thrown is a falsy value", function() {
var matcher = jasmineUnderTest.matchers.toThrowMatching(), var matcher = jasmineUnderTest.matchers.toThrowMatching({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() { fn = function() {
throw undefined; throw undefined;
}, },
@@ -58,8 +60,10 @@ describe("toThrowMatching", function() {
}); });
it("fails if the argument is a function that returns false when called with the error", function() { it("fails if the argument is a function that returns false when called with the error", function() {
var matcher = jasmineUnderTest.matchers.toThrowMatching(), var matcher = jasmineUnderTest.matchers.toThrowMatching({
predicate = function(e) { return e.message === "oh no" }, pp: jasmineUnderTest.makePrettyPrinter()
}),
predicate = function(e) { return e.message === "oh no" },
fn = function() { fn = function() {
throw new TypeError("nope"); throw new TypeError("nope");
}, },
+11 -5
View File
@@ -24,7 +24,8 @@ describe("toThrow", function() {
it("passes if it throws but there is no expected", function() { it("passes if it throws but there is no expected", function() {
var util = { var util = {
equals: jasmine.createSpy('delegated-equal').and.returnValue(true) equals: jasmine.createSpy('delegated-equal').and.returnValue(true),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toThrow(util), matcher = jasmineUnderTest.matchers.toThrow(util),
fn = function() { fn = function() {
@@ -39,7 +40,9 @@ describe("toThrow", function() {
}); });
it("passes even if what is thrown is falsy", function() { it("passes even if what is thrown is falsy", function() {
var matcher = jasmineUnderTest.matchers.toThrow(), var matcher = jasmineUnderTest.matchers.toThrow({
pp: jasmineUnderTest.makePrettyPrinter()
}),
fn = function() { fn = function() {
throw undefined; throw undefined;
}, },
@@ -52,7 +55,8 @@ describe("toThrow", function() {
it("passes if what is thrown is equivalent to what is expected", function() { it("passes if what is thrown is equivalent to what is expected", function() {
var util = { var util = {
equals: jasmine.createSpy('delegated-equal').and.returnValue(true) equals: jasmine.createSpy('delegated-equal').and.returnValue(true),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toThrow(util), matcher = jasmineUnderTest.matchers.toThrow(util),
fn = function() { fn = function() {
@@ -68,7 +72,8 @@ describe("toThrow", function() {
it("fails if what is thrown is not equivalent to what is expected", function() { it("fails if what is thrown is not equivalent to what is expected", function() {
var util = { var util = {
equals: jasmine.createSpy('delegated-equal').and.returnValue(false) equals: jasmine.createSpy('delegated-equal').and.returnValue(false),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toThrow(util), matcher = jasmineUnderTest.matchers.toThrow(util),
fn = function() { fn = function() {
@@ -84,7 +89,8 @@ describe("toThrow", function() {
it("fails if what is thrown is not equivalent to undefined", function() { it("fails if what is thrown is not equivalent to undefined", function() {
var util = { var util = {
equals: jasmine.createSpy('delegated-equal').and.returnValue(false) equals: jasmine.createSpy('delegated-equal').and.returnValue(false),
pp: jasmineUnderTest.makePrettyPrinter()
}, },
matcher = jasmineUnderTest.matchers.toThrow(util), matcher = jasmineUnderTest.matchers.toThrow(util),
fn = function() { fn = function() {
+12 -9
View File
@@ -1,43 +1,46 @@
describe('jasmineUnderTest.pp (HTML Dependent)', function() { describe('PrettyPrinter (HTML Dependent)', function() {
it('should stringify non-element HTML nodes properly', function() { it('should stringify non-element HTML nodes properly', function() {
var sampleNode = document.createTextNode(''); var sampleNode = document.createTextNode('');
expect(jasmineUnderTest.pp(sampleNode)).toEqual('HTMLNode'); var pp = jasmineUnderTest.makePrettyPrinter();
expect(jasmineUnderTest.pp({ foo: sampleNode })).toEqual( expect(pp(sampleNode)).toEqual('HTMLNode');
'Object({ foo: HTMLNode })' expect(pp({ foo: sampleNode })).toEqual('Object({ foo: HTMLNode })');
);
}); });
it('should stringify empty HTML elements as their opening tags', function() { it('should stringify empty HTML elements as their opening tags', function() {
var simple = document.createElement('div'); var simple = document.createElement('div');
var pp = jasmineUnderTest.makePrettyPrinter();
simple.className = 'foo'; simple.className = 'foo';
expect(jasmineUnderTest.pp(simple)).toEqual('<div class="foo">'); expect(pp(simple)).toEqual('<div class="foo">');
}); });
it('should stringify non-empty HTML elements as tags with placeholders', function() { it('should stringify non-empty HTML elements as tags with placeholders', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var nonEmpty = document.createElement('div'); var nonEmpty = document.createElement('div');
nonEmpty.className = 'foo'; nonEmpty.className = 'foo';
nonEmpty.innerHTML = '<p>Irrelevant</p>'; nonEmpty.innerHTML = '<p>Irrelevant</p>';
expect(jasmineUnderTest.pp(nonEmpty)).toEqual('<div class="foo">...</div>'); expect(pp(nonEmpty)).toEqual('<div class="foo">...</div>');
}); });
it("should print Firefox's wrapped native objects correctly", function() { it("should print Firefox's wrapped native objects correctly", function() {
if (jasmine.getEnv().firefoxVersion) { if (jasmine.getEnv().firefoxVersion) {
var pp = jasmineUnderTest.makePrettyPrinter();
try { try {
new CustomEvent(); new CustomEvent();
} catch (e) { } catch (e) {
var err = e; var err = e;
} }
// Different versions of FF produce different error messages. // Different versions of FF produce different error messages.
expect(jasmineUnderTest.pp(err)).toMatch( expect(pp(err)).toMatch(
/Not enough arguments|CustomEvent requires at least 1 argument, but only 0 were passed/ /Not enough arguments|CustomEvent requires at least 1 argument, but only 0 were passed/
); );
} }
}); });
it('should stringify HTML element with text and attributes', function() { it('should stringify HTML element with text and attributes', function() {
var pp = jasmineUnderTest.makePrettyPrinter();
var el = document.createElement('div'); var el = document.createElement('div');
el.setAttribute('things', 'foo'); el.setAttribute('things', 'foo');
el.innerHTML = 'foo'; el.innerHTML = 'foo';
expect(jasmineUnderTest.pp(el)).toEqual('<div things="foo">...</div>'); expect(pp(el)).toEqual('<div things="foo">...</div>');
}); });
}); });
+16 -6
View File
@@ -309,12 +309,25 @@ getJasmineRequireObj().Env = function(j$) {
return 'suite' + nextSuiteId++; return 'suite' + nextSuiteId++;
}; };
var makePrettyPrinter = function() {
return j$.makePrettyPrinter();
};
var makeMatchersUtil = function() {
var customEqualityTesters =
runnableResources[currentRunnable().id].customEqualityTesters;
return new j$.MatchersUtil({
customTesters: customEqualityTesters,
pp: makePrettyPrinter()
});
};
var expectationFactory = function(actual, spec) { var expectationFactory = function(actual, spec) {
var customEqualityTesters = var customEqualityTesters =
runnableResources[spec.id].customEqualityTesters; runnableResources[spec.id].customEqualityTesters;
return j$.Expectation.factory({ return j$.Expectation.factory({
util: new j$.MatchersUtil({ customTesters: customEqualityTesters }), util: makeMatchersUtil(),
customEqualityTesters: customEqualityTesters, customEqualityTesters: customEqualityTesters,
customMatchers: runnableResources[spec.id].customMatchers, customMatchers: runnableResources[spec.id].customMatchers,
actual: actual, actual: actual,
@@ -327,11 +340,8 @@ getJasmineRequireObj().Env = function(j$) {
}; };
var asyncExpectationFactory = function(actual, spec) { var asyncExpectationFactory = function(actual, spec) {
var customEqualityTesters =
runnableResources[spec.id].customEqualityTesters;
return j$.Expectation.asyncFactory({ return j$.Expectation.asyncFactory({
util: new j$.MatchersUtil({ customTesters: customEqualityTesters }), util: makeMatchersUtil(),
customEqualityTesters: runnableResources[spec.id].customEqualityTesters, customEqualityTesters: runnableResources[spec.id].customEqualityTesters,
customAsyncMatchers: runnableResources[spec.id].customAsyncMatchers, customAsyncMatchers: runnableResources[spec.id].customAsyncMatchers,
actual: actual, actual: actual,
@@ -1143,7 +1153,7 @@ getJasmineRequireObj().Env = function(j$) {
message += error; message += error;
} else { } else {
// pretty print all kind of objects. This includes arrays. // pretty print all kind of objects. This includes arrays.
message += j$.pp(error); message += makePrettyPrinter()(error);
} }
} }
+1 -1
View File
@@ -141,7 +141,7 @@ getJasmineRequireObj().Expectation = function(j$) {
args = args.slice(); args = args.slice();
args.unshift(true); args.unshift(true);
args.unshift(matcherName); args.unshift(matcherName);
return util.buildFailureMessage.apply(null, args); return util.buildFailureMessage.apply(util, args);
} }
function negate(result) { function negate(result) {
+1 -1
View File
@@ -44,7 +44,7 @@ getJasmineRequireObj().Expector = function(j$) {
var args = self.args.slice(); var args = self.args.slice();
args.unshift(false); args.unshift(false);
args.unshift(self.matcherName); args.unshift(self.matcherName);
return self.util.buildFailureMessage.apply(null, args); return self.util.buildFailureMessage.apply(self.util, args);
} else if (j$.isFunction_(result.message)) { } else if (j$.isFunction_(result.message)) {
return result.message(); return result.message();
} else { } else {
+25 -18
View File
@@ -1,5 +1,5 @@
getJasmineRequireObj().pp = function(j$) { getJasmineRequireObj().makePrettyPrinter = function(j$) {
function PrettyPrinter() { function SinglePrettyPrintRun() {
this.ppNestLevel_ = 0; this.ppNestLevel_ = 0;
this.seen = []; this.seen = [];
this.length = 0; this.length = 0;
@@ -21,7 +21,7 @@ getJasmineRequireObj().pp = function(j$) {
} }
} }
PrettyPrinter.prototype.format = function(value) { SinglePrettyPrintRun.prototype.format = function(value) {
this.ppNestLevel_++; this.ppNestLevel_++;
try { try {
if (j$.util.isUndefined(value)) { if (j$.util.isUndefined(value)) {
@@ -95,7 +95,7 @@ getJasmineRequireObj().pp = function(j$) {
} }
}; };
PrettyPrinter.prototype.iterateObject = function(obj, fn) { SinglePrettyPrintRun.prototype.iterateObject = function(obj, fn) {
var objKeys = keys(obj, j$.isArray_(obj)); var objKeys = keys(obj, j$.isArray_(obj));
var isGetter = function isGetter(prop) {}; var isGetter = function isGetter(prop) {};
@@ -114,15 +114,15 @@ getJasmineRequireObj().pp = function(j$) {
return objKeys.length > length; return objKeys.length > length;
}; };
PrettyPrinter.prototype.emitScalar = function(value) { SinglePrettyPrintRun.prototype.emitScalar = function(value) {
this.append(value); this.append(value);
}; };
PrettyPrinter.prototype.emitString = function(value) { SinglePrettyPrintRun.prototype.emitString = function(value) {
this.append("'" + value + "'"); this.append("'" + value + "'");
}; };
PrettyPrinter.prototype.emitArray = function(array) { SinglePrettyPrintRun.prototype.emitArray = function(array) {
if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) {
this.append('Array'); this.append('Array');
return; return;
@@ -158,7 +158,7 @@ getJasmineRequireObj().pp = function(j$) {
this.append(' ]'); this.append(' ]');
}; };
PrettyPrinter.prototype.emitSet = function(set) { SinglePrettyPrintRun.prototype.emitSet = function(set) {
if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) {
this.append('Set'); this.append('Set');
return; return;
@@ -183,7 +183,7 @@ getJasmineRequireObj().pp = function(j$) {
this.append(' )'); this.append(' )');
}; };
PrettyPrinter.prototype.emitMap = function(map) { SinglePrettyPrintRun.prototype.emitMap = function(map) {
if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) {
this.append('Map'); this.append('Map');
return; return;
@@ -208,7 +208,7 @@ getJasmineRequireObj().pp = function(j$) {
this.append(' )'); this.append(' )');
}; };
PrettyPrinter.prototype.emitObject = function(obj) { SinglePrettyPrintRun.prototype.emitObject = function(obj) {
var ctor = obj.constructor, var ctor = obj.constructor,
constructorName; constructorName;
@@ -244,7 +244,7 @@ getJasmineRequireObj().pp = function(j$) {
this.append(' })'); this.append(' })');
}; };
PrettyPrinter.prototype.emitTypedArray = function(arr) { SinglePrettyPrintRun.prototype.emitTypedArray = function(arr) {
var constructorName = j$.fnNameFor(arr.constructor), var constructorName = j$.fnNameFor(arr.constructor),
limitedArray = Array.prototype.slice.call( limitedArray = Array.prototype.slice.call(
arr, arr,
@@ -260,7 +260,7 @@ getJasmineRequireObj().pp = function(j$) {
this.append(constructorName + ' [ ' + itemsString + ' ]'); this.append(constructorName + ' [ ' + itemsString + ' ]');
}; };
PrettyPrinter.prototype.emitDomElement = function(el) { SinglePrettyPrintRun.prototype.emitDomElement = function(el) {
var tagName = el.tagName.toLowerCase(), var tagName = el.tagName.toLowerCase(),
attrs = el.attributes, attrs = el.attributes,
i, i,
@@ -286,7 +286,11 @@ getJasmineRequireObj().pp = function(j$) {
this.append(out); this.append(out);
}; };
PrettyPrinter.prototype.formatProperty = function(obj, property, isGetter) { SinglePrettyPrintRun.prototype.formatProperty = function(
obj,
property,
isGetter
) {
this.append(property); this.append(property);
this.append(': '); this.append(': ');
if (isGetter) { if (isGetter) {
@@ -296,7 +300,7 @@ getJasmineRequireObj().pp = function(j$) {
} }
}; };
PrettyPrinter.prototype.append = function(value) { SinglePrettyPrintRun.prototype.append = function(value) {
// This check protects us from the rare case where an object has overriden // This check protects us from the rare case where an object has overriden
// `toString()` with an invalid implementation (returning a non-string). // `toString()` with an invalid implementation (returning a non-string).
if (typeof value !== 'string') { if (typeof value !== 'string') {
@@ -360,9 +364,12 @@ getJasmineRequireObj().pp = function(j$) {
return extraKeys; return extraKeys;
} }
return function(value) {
var prettyPrinter = new PrettyPrinter(); return function() {
prettyPrinter.format(value); return function(value) {
return prettyPrinter.stringParts.join(''); var prettyPrinter = new SinglePrettyPrintRun();
prettyPrinter.format(value);
return prettyPrinter.stringParts.join('');
};
}; };
}; };
+4 -1
View File
@@ -7,7 +7,10 @@ getJasmineRequireObj().Spy = function(j$) {
}; };
})(); })();
var matchersUtil = new j$.MatchersUtil(); var matchersUtil = new j$.MatchersUtil({
customTesters: [],
pp: j$.makePrettyPrinter()
});
/** /**
* _Note:_ Do not construct this directly, use {@link spyOn}, {@link spyOnProperty}, {@link jasmine.createSpy}, or {@link jasmine.createSpyObj} * _Note:_ Do not construct this directly, use {@link spyOn}, {@link spyOnProperty}, {@link jasmine.createSpy}, or {@link jasmine.createSpyObj}
+4 -4
View File
@@ -11,7 +11,7 @@ getJasmineRequireObj().toBeRejectedWith = function(j$) {
* @example * @example
* return expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); * return expectAsync(aPromise).toBeRejectedWith({prop: 'value'});
*/ */
return function toBeRejectedWith(util) { return function toBeRejectedWith(matchersUtil) {
return { return {
compare: function(actualPromise, expectedValue) { compare: function(actualPromise, expectedValue) {
if (!j$.isPromiseLike(actualPromise)) { if (!j$.isPromiseLike(actualPromise)) {
@@ -21,7 +21,7 @@ getJasmineRequireObj().toBeRejectedWith = function(j$) {
function prefix(passed) { function prefix(passed) {
return 'Expected a promise ' + return 'Expected a promise ' +
(passed ? 'not ' : '') + (passed ? 'not ' : '') +
'to be rejected with ' + j$.pp(expectedValue); 'to be rejected with ' + matchersUtil.pp(expectedValue);
} }
return actualPromise.then( return actualPromise.then(
@@ -32,7 +32,7 @@ getJasmineRequireObj().toBeRejectedWith = function(j$) {
}; };
}, },
function(actualValue) { function(actualValue) {
if (util.equals(actualValue, expectedValue)) { if (matchersUtil.equals(actualValue, expectedValue)) {
return { return {
pass: true, pass: true,
message: prefix(true) + '.' message: prefix(true) + '.'
@@ -40,7 +40,7 @@ getJasmineRequireObj().toBeRejectedWith = function(j$) {
} else { } else {
return { return {
pass: false, pass: false,
message: prefix(false) + ' but it was rejected with ' + j$.pp(actualValue) + '.' message: prefix(false) + ' but it was rejected with ' + matchersUtil.pp(actualValue) + '.'
}; };
} }
} }
@@ -14,14 +14,14 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) {
* await expectAsync(aPromise).toBeRejectedWithError('Error message'); * await expectAsync(aPromise).toBeRejectedWithError('Error message');
* return expectAsync(aPromise).toBeRejectedWithError(/Error message/); * return expectAsync(aPromise).toBeRejectedWithError(/Error message/);
*/ */
return function toBeRejectedWithError() { return function toBeRejectedWithError(matchersUtil) {
return { return {
compare: function(actualPromise, arg1, arg2) { compare: function(actualPromise, arg1, arg2) {
if (!j$.isPromiseLike(actualPromise)) { if (!j$.isPromiseLike(actualPromise)) {
throw new Error('Expected toBeRejectedWithError to be called on a promise.'); throw new Error('Expected toBeRejectedWithError to be called on a promise.');
} }
var expected = getExpectedFromArgs(arg1, arg2); var expected = getExpectedFromArgs(arg1, arg2, matchersUtil);
return actualPromise.then( return actualPromise.then(
function() { function() {
@@ -30,15 +30,15 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) {
message: 'Expected a promise to be rejected but it was resolved.' message: 'Expected a promise to be rejected but it was resolved.'
}; };
}, },
function(actualValue) { return matchError(actualValue, expected); } function(actualValue) { return matchError(actualValue, expected, matchersUtil); }
); );
} }
}; };
}; };
function matchError(actual, expected) { function matchError(actual, expected, matchersUtil) {
if (!j$.isError_(actual)) { if (!j$.isError_(actual)) {
return fail(expected, 'rejected with ' + j$.pp(actual)); return fail(expected, 'rejected with ' + matchersUtil.pp(actual));
} }
if (!(actual instanceof expected.error)) { if (!(actual instanceof expected.error)) {
@@ -55,7 +55,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) {
return pass(expected); return pass(expected);
} }
return fail(expected, 'rejected with ' + j$.pp(actual)); return fail(expected, 'rejected with ' + matchersUtil.pp(actual));
} }
function pass(expected) { function pass(expected) {
@@ -73,7 +73,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) {
} }
function getExpectedFromArgs(arg1, arg2) { function getExpectedFromArgs(arg1, arg2, matchersUtil) {
var error, message; var error, message;
if (isErrorConstructor(arg1)) { if (isErrorConstructor(arg1)) {
@@ -87,7 +87,7 @@ getJasmineRequireObj().toBeRejectedWithError = function(j$) {
return { return {
error: error, error: error,
message: message, message: message,
printValue: j$.fnNameFor(error) + (typeof message === 'undefined' ? '' : ': ' + j$.pp(message)) printValue: j$.fnNameFor(error) + (typeof message === 'undefined' ? '' : ': ' + matchersUtil.pp(message))
}; };
} }
+4 -4
View File
@@ -11,7 +11,7 @@ getJasmineRequireObj().toBeResolvedTo = function(j$) {
* @example * @example
* return expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); * return expectAsync(aPromise).toBeResolvedTo({prop: 'value'});
*/ */
return function toBeResolvedTo(util) { return function toBeResolvedTo(matchersUtil) {
return { return {
compare: function(actualPromise, expectedValue) { compare: function(actualPromise, expectedValue) {
if (!j$.isPromiseLike(actualPromise)) { if (!j$.isPromiseLike(actualPromise)) {
@@ -21,12 +21,12 @@ getJasmineRequireObj().toBeResolvedTo = function(j$) {
function prefix(passed) { function prefix(passed) {
return 'Expected a promise ' + return 'Expected a promise ' +
(passed ? 'not ' : '') + (passed ? 'not ' : '') +
'to be resolved to ' + j$.pp(expectedValue); 'to be resolved to ' + matchersUtil.pp(expectedValue);
} }
return actualPromise.then( return actualPromise.then(
function(actualValue) { function(actualValue) {
if (util.equals(actualValue, expectedValue)) { if (matchersUtil.equals(actualValue, expectedValue)) {
return { return {
pass: true, pass: true,
message: prefix(true) + '.' message: prefix(true) + '.'
@@ -34,7 +34,7 @@ getJasmineRequireObj().toBeResolvedTo = function(j$) {
} else { } else {
return { return {
pass: false, pass: false,
message: prefix(false) + ' but it was resolved to ' + j$.pp(actualValue) + '.' message: prefix(false) + ' but it was resolved to ' + matchersUtil.pp(actualValue) + '.'
}; };
} }
}, },
+18 -20
View File
@@ -1,14 +1,11 @@
getJasmineRequireObj().MatchersUtil = function(j$) { getJasmineRequireObj().MatchersUtil = function(j$) {
// TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter? // TODO: convert all uses of j$.pp to use the injected pp
function MatchersUtil(options) { function MatchersUtil(options) {
options = options || {}; options = options || {};
this.customTesters_ = options.customTesters || []; this.customTesters_ = options.customTesters || [];
this.pp = options.pp || function() {};
if (!j$.isArray_(this.customTesters_)) { };
throw new Error("MatchersUtil requires custom equality testers");
}
}
MatchersUtil.prototype.contains = function(haystack, needle, customTesters) { MatchersUtil.prototype.contains = function(haystack, needle, customTesters) {
if (j$.isSet(haystack)) { if (j$.isSet(haystack)) {
@@ -30,6 +27,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
}; };
MatchersUtil.prototype.buildFailureMessage = function() { MatchersUtil.prototype.buildFailureMessage = function() {
var self = this;
var args = Array.prototype.slice.call(arguments, 0), var args = Array.prototype.slice.call(arguments, 0),
matcherName = args[0], matcherName = args[0],
isNot = args[1], isNot = args[1],
@@ -38,7 +36,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); });
var message = 'Expected ' + var message = 'Expected ' +
j$.pp(actual) + self.pp(actual) +
(isNot ? ' not ' : ' ') + (isNot ? ' not ' : ' ') +
englishyPredicate; englishyPredicate;
@@ -240,7 +238,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
for (i = 0; i < aLength || i < bLength; i++) { for (i = 0; i < aLength || i < bLength; i++) {
diffBuilder.withPath(i, function() { diffBuilder.withPath(i, function() {
if (i >= bLength) { if (i >= bLength) {
diffBuilder.record(a[i], void 0, actualArrayIsLongerFormatter); diffBuilder.record(a[i], void 0, actualArrayIsLongerFormatter.bind(null, self.pp));
result = false; result = false;
} else { } else {
result = self.eq_(i < aLength ? a[i] : void 0, i < bLength ? b[i] : void 0, aStack, bStack, customTesters, diffBuilder) && result; result = self.eq_(i < aLength ? a[i] : void 0, i < bLength ? b[i] : void 0, aStack, bStack, customTesters, diffBuilder) && result;
@@ -357,7 +355,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
a instanceof aCtor && b instanceof bCtor && a instanceof aCtor && b instanceof bCtor &&
!(aCtor instanceof aCtor && bCtor instanceof bCtor)) { !(aCtor instanceof aCtor && bCtor instanceof bCtor)) {
diffBuilder.record(a, b, constructorsAreDifferentFormatter); diffBuilder.record(a, b, constructorsAreDifferentFormatter.bind(null, this.pp));
return false; return false;
} }
} }
@@ -368,7 +366,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
// Ensure that both objects contain the same number of properties before comparing deep equality. // Ensure that both objects contain the same number of properties before comparing deep equality.
if (keys(b, className == '[object Array]').length !== size) { if (keys(b, className == '[object Array]').length !== size) {
diffBuilder.record(a, b, objectKeysAreDifferentFormatter); diffBuilder.record(a, b, objectKeysAreDifferentFormatter.bind(null, this.pp));
return false; return false;
} }
@@ -376,7 +374,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
key = aKeys[i]; key = aKeys[i];
// Deep compare each member // Deep compare each member
if (!j$.util.has(b, key)) { if (!j$.util.has(b, key)) {
diffBuilder.record(a, b, objectKeysAreDifferentFormatter); diffBuilder.record(a, b, objectKeysAreDifferentFormatter.bind(null, this.pp));
result = false; result = false;
continue; continue;
} }
@@ -433,11 +431,11 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
return typeof obj === 'function'; return typeof obj === 'function';
} }
function objectKeysAreDifferentFormatter(actual, expected, path) { function objectKeysAreDifferentFormatter(pp, actual, expected, path) {
var missingProperties = j$.util.objectDifference(expected, actual), var missingProperties = j$.util.objectDifference(expected, actual),
extraProperties = j$.util.objectDifference(actual, expected), extraProperties = j$.util.objectDifference(actual, expected),
missingPropertiesMessage = formatKeyValuePairs(missingProperties), missingPropertiesMessage = formatKeyValuePairs(pp, missingProperties),
extraPropertiesMessage = formatKeyValuePairs(extraProperties), extraPropertiesMessage = formatKeyValuePairs(pp, extraProperties),
messages = []; messages = [];
if (!path.depth()) { if (!path.depth()) {
@@ -455,7 +453,7 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
return messages.join('\n'); return messages.join('\n');
} }
function constructorsAreDifferentFormatter(actual, expected, path) { function constructorsAreDifferentFormatter(pp, actual, expected, path) {
if (!path.depth()) { if (!path.depth()) {
path = 'object'; path = 'object';
} }
@@ -463,20 +461,20 @@ getJasmineRequireObj().MatchersUtil = function(j$) {
return 'Expected ' + return 'Expected ' +
path + ' to be a kind of ' + path + ' to be a kind of ' +
j$.fnNameFor(expected.constructor) + j$.fnNameFor(expected.constructor) +
', but was ' + j$.pp(actual) + '.'; ', but was ' + pp(actual) + '.';
} }
function actualArrayIsLongerFormatter(actual, expected, path) { function actualArrayIsLongerFormatter(pp, actual, expected, path) {
return 'Unexpected ' + return 'Unexpected ' +
path + (path.depth() ? ' = ' : '') + path + (path.depth() ? ' = ' : '') +
j$.pp(actual) + pp(actual) +
' in array.'; ' in array.';
} }
function formatKeyValuePairs(obj) { function formatKeyValuePairs(pp, obj) {
var formatted = ''; var formatted = '';
for (var key in obj) { for (var key in obj) {
formatted += '\n ' + key + ': ' + j$.pp(obj[key]); formatted += '\n ' + key + ': ' + pp(obj[key]);
} }
return formatted; return formatted;
} }
+3 -3
View File
@@ -12,11 +12,11 @@ getJasmineRequireObj().toBeInstanceOf = function(j$) {
* expect(3).toBeInstanceOf(Number); * expect(3).toBeInstanceOf(Number);
* expect(new Error()).toBeInstanceOf(Error); * expect(new Error()).toBeInstanceOf(Error);
*/ */
function toBeInstanceOf() { function toBeInstanceOf(matchersUtil) {
return { return {
compare: function(actual, expected) { compare: function(actual, expected) {
var actualType = actual && actual.constructor ? j$.fnNameFor(actual.constructor) : j$.pp(actual), var actualType = actual && actual.constructor ? j$.fnNameFor(actual.constructor) : matchersUtil.pp(actual),
expectedType = expected ? j$.fnNameFor(expected) : j$.pp(expected), expectedType = expected ? j$.fnNameFor(expected) : matchersUtil.pp(expected),
expectedMatcher, expectedMatcher,
pass; pass;
+2 -2
View File
@@ -7,7 +7,7 @@ getJasmineRequireObj().toBeNaN = function(j$) {
* @example * @example
* expect(thing).toBeNaN(); * expect(thing).toBeNaN();
*/ */
function toBeNaN() { function toBeNaN(matchersUtil) {
return { return {
compare: function(actual) { compare: function(actual) {
var result = { var result = {
@@ -17,7 +17,7 @@ getJasmineRequireObj().toBeNaN = function(j$) {
if (result.pass) { if (result.pass) {
result.message = 'Expected actual not to be NaN.'; result.message = 'Expected actual not to be NaN.';
} else { } else {
result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be NaN.'; }; result.message = function() { return 'Expected ' + matchersUtil.pp(actual) + ' to be NaN.'; };
} }
return result; return result;
+2 -2
View File
@@ -7,7 +7,7 @@ getJasmineRequireObj().toBeNegativeInfinity = function(j$) {
* @example * @example
* expect(thing).toBeNegativeInfinity(); * expect(thing).toBeNegativeInfinity();
*/ */
function toBeNegativeInfinity() { function toBeNegativeInfinity(matchersUtil) {
return { return {
compare: function(actual) { compare: function(actual) {
var result = { var result = {
@@ -17,7 +17,7 @@ getJasmineRequireObj().toBeNegativeInfinity = function(j$) {
if (result.pass) { if (result.pass) {
result.message = 'Expected actual not to be -Infinity.'; result.message = 'Expected actual not to be -Infinity.';
} else { } else {
result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be -Infinity.'; }; result.message = function() { return 'Expected ' + matchersUtil.pp(actual) + ' to be -Infinity.'; };
} }
return result; return result;
+2 -2
View File
@@ -7,7 +7,7 @@ getJasmineRequireObj().toBePositiveInfinity = function(j$) {
* @example * @example
* expect(thing).toBePositiveInfinity(); * expect(thing).toBePositiveInfinity();
*/ */
function toBePositiveInfinity() { function toBePositiveInfinity(matchersUtil) {
return { return {
compare: function(actual) { compare: function(actual) {
var result = { var result = {
@@ -17,7 +17,7 @@ getJasmineRequireObj().toBePositiveInfinity = function(j$) {
if (result.pass) { if (result.pass) {
result.message = 'Expected actual not to be Infinity.'; result.message = 'Expected actual not to be Infinity.';
} else { } else {
result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be Infinity.'; }; result.message = function() { return 'Expected ' + matchersUtil.pp(actual) + ' to be Infinity.'; };
} }
return result; return result;
+2 -2
View File
@@ -11,13 +11,13 @@ getJasmineRequireObj().toHaveBeenCalled = function(j$) {
* expect(mySpy).toHaveBeenCalled(); * expect(mySpy).toHaveBeenCalled();
* expect(mySpy).not.toHaveBeenCalled(); * expect(mySpy).not.toHaveBeenCalled();
*/ */
function toHaveBeenCalled() { function toHaveBeenCalled(matchersUtil) {
return { return {
compare: function(actual) { compare: function(actual) {
var result = {}; var result = {};
if (!j$.isSpy(actual)) { if (!j$.isSpy(actual)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); throw new Error(getErrorMsg('Expected a spy, but got ' + matchersUtil.pp(actual) + '.'));
} }
if (arguments.length > 1) { if (arguments.length > 1) {
+3 -3
View File
@@ -11,14 +11,14 @@ getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) {
* @example * @example
* expect(mySpy).toHaveBeenCalledBefore(otherSpy); * expect(mySpy).toHaveBeenCalledBefore(otherSpy);
*/ */
function toHaveBeenCalledBefore() { function toHaveBeenCalledBefore(matchersUtil) {
return { return {
compare: function(firstSpy, latterSpy) { compare: function(firstSpy, latterSpy) {
if (!j$.isSpy(firstSpy)) { if (!j$.isSpy(firstSpy)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(firstSpy) + '.')); throw new Error(getErrorMsg('Expected a spy, but got ' + matchersUtil.pp(firstSpy) + '.'));
} }
if (!j$.isSpy(latterSpy)) { if (!j$.isSpy(latterSpy)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(latterSpy) + '.')); throw new Error(getErrorMsg('Expected a spy, but got ' + matchersUtil.pp(latterSpy) + '.'));
} }
var result = { pass: false }; var result = { pass: false };
+2 -2
View File
@@ -11,11 +11,11 @@ getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) {
* @example * @example
* expect(mySpy).toHaveBeenCalledTimes(3); * expect(mySpy).toHaveBeenCalledTimes(3);
*/ */
function toHaveBeenCalledTimes() { function toHaveBeenCalledTimes(matchersUtil) {
return { return {
compare: function(actual, expected) { compare: function(actual, expected) {
if (!j$.isSpy(actual)) { if (!j$.isSpy(actual)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); throw new Error(getErrorMsg('Expected a spy, but got ' + matchersUtil.pp(actual) + '.'));
} }
var args = Array.prototype.slice.call(arguments, 0), var args = Array.prototype.slice.call(arguments, 0),
+8 -8
View File
@@ -11,7 +11,7 @@ getJasmineRequireObj().toHaveBeenCalledWith = function(j$) {
* @example * @example
* expect(mySpy).toHaveBeenCalledWith('foo', 'bar', 2); * expect(mySpy).toHaveBeenCalledWith('foo', 'bar', 2);
*/ */
function toHaveBeenCalledWith(util) { function toHaveBeenCalledWith(matchersUtil) {
return { return {
compare: function() { compare: function() {
var args = Array.prototype.slice.call(arguments, 0), var args = Array.prototype.slice.call(arguments, 0),
@@ -20,40 +20,40 @@ getJasmineRequireObj().toHaveBeenCalledWith = function(j$) {
result = { pass: false }; result = { pass: false };
if (!j$.isSpy(actual)) { if (!j$.isSpy(actual)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.')); throw new Error(getErrorMsg('Expected a spy, but got ' + matchersUtil.pp(actual) + '.'));
} }
if (!actual.calls.any()) { if (!actual.calls.any()) {
result.message = function() { result.message = function() {
return 'Expected spy ' + actual.and.identity + ' to have been called with:\n' + return 'Expected spy ' + actual.and.identity + ' to have been called with:\n' +
' ' + j$.pp(expectedArgs) + ' ' + matchersUtil.pp(expectedArgs) +
'\nbut it was never called.'; '\nbut it was never called.';
}; };
return result; return result;
} }
if (util.contains(actual.calls.allArgs(), expectedArgs)) { if (matchersUtil.contains(actual.calls.allArgs(), expectedArgs)) {
result.pass = true; result.pass = true;
result.message = function() { result.message = function() {
return 'Expected spy ' + actual.and.identity + ' not to have been called with:\n' + return 'Expected spy ' + actual.and.identity + ' not to have been called with:\n' +
' ' + j$.pp(expectedArgs) + ' ' + matchersUtil.pp(expectedArgs) +
'\nbut it was.'; '\nbut it was.';
}; };
} else { } else {
result.message = function() { result.message = function() {
var prettyPrintedCalls = actual.calls.allArgs().map(function(argsForCall) { var prettyPrintedCalls = actual.calls.allArgs().map(function(argsForCall) {
return ' ' + j$.pp(argsForCall); return ' ' + matchersUtil.pp(argsForCall);
}); });
var diffs = actual.calls.allArgs().map(function(argsForCall, callIx) { var diffs = actual.calls.allArgs().map(function(argsForCall, callIx) {
var diffBuilder = new j$.DiffBuilder(); var diffBuilder = new j$.DiffBuilder();
util.equals(argsForCall, expectedArgs, diffBuilder); matchersUtil.equals(argsForCall, expectedArgs, diffBuilder);
return 'Call ' + callIx + ':\n' + return 'Call ' + callIx + ':\n' +
diffBuilder.getMessage().replace(/^/mg, ' '); diffBuilder.getMessage().replace(/^/mg, ' ');
}); });
return 'Expected spy ' + actual.and.identity + ' to have been called with:\n' + return 'Expected spy ' + actual.and.identity + ' to have been called with:\n' +
' ' + j$.pp(expectedArgs) + '\n' + '' + ' ' + matchersUtil.pp(expectedArgs) + '\n' + '' +
'but actual calls were:\n' + 'but actual calls were:\n' +
prettyPrintedCalls.join(',\n') + '.\n\n' + prettyPrintedCalls.join(',\n') + '.\n\n' +
diffs.join('\n'); diffs.join('\n');
+2 -2
View File
@@ -10,11 +10,11 @@ getJasmineRequireObj().toHaveClass = function(j$) {
* el.className = 'foo bar baz'; * el.className = 'foo bar baz';
* expect(el).toHaveClass('bar'); * expect(el).toHaveClass('bar');
*/ */
function toHaveClass() { function toHaveClass(matchersUtil) {
return { return {
compare: function(actual, expected) { compare: function(actual, expected) {
if (!isElement(actual)) { if (!isElement(actual)) {
throw new Error(j$.pp(actual) + ' is not a DOM element'); throw new Error(matchersUtil.pp(actual) + ' is not a DOM element');
} }
return { return {
+5 -5
View File
@@ -12,7 +12,7 @@ getJasmineRequireObj().toThrow = function(j$) {
* expect(function() { return 'things'; }).toThrow('foo'); * expect(function() { return 'things'; }).toThrow('foo');
* expect(function() { return 'stuff'; }).toThrow(); * expect(function() { return 'stuff'; }).toThrow();
*/ */
function toThrow(util) { function toThrow(matchersUtil) {
return { return {
compare: function(actual, expected) { compare: function(actual, expected) {
var result = { pass: false }, var result = { pass: false },
@@ -37,16 +37,16 @@ getJasmineRequireObj().toThrow = function(j$) {
if (arguments.length == 1) { if (arguments.length == 1) {
result.pass = true; result.pass = true;
result.message = function() { return 'Expected function not to throw, but it threw ' + j$.pp(thrown) + '.'; }; result.message = function() { return 'Expected function not to throw, but it threw ' + matchersUtil.pp(thrown) + '.'; };
return result; return result;
} }
if (util.equals(thrown, expected)) { if (matchersUtil.equals(thrown, expected)) {
result.pass = true; result.pass = true;
result.message = function() { return 'Expected function not to throw ' + j$.pp(expected) + '.'; }; result.message = function() { return 'Expected function not to throw ' + matchersUtil.pp(expected) + '.'; };
} else { } else {
result.message = function() { return 'Expected function to throw ' + j$.pp(expected) + ', but it threw ' + j$.pp(thrown) + '.'; }; result.message = function() { return 'Expected function to throw ' + matchersUtil.pp(expected) + ', but it threw ' + matchersUtil.pp(thrown) + '.'; };
} }
return result; return result;
+5 -5
View File
@@ -16,7 +16,7 @@ getJasmineRequireObj().toThrowError = function(j$) {
* expect(function() { return 'other'; }).toThrowError(/foo/); * expect(function() { return 'other'; }).toThrowError(/foo/);
* expect(function() { return 'other'; }).toThrowError(); * expect(function() { return 'other'; }).toThrowError();
*/ */
function toThrowError () { function toThrowError(matchersUtil) {
return { return {
compare: function(actual) { compare: function(actual) {
var errorMatcher = getMatcher.apply(null, arguments), var errorMatcher = getMatcher.apply(null, arguments),
@@ -34,7 +34,7 @@ getJasmineRequireObj().toThrowError = function(j$) {
} }
if (!j$.isError_(thrown)) { if (!j$.isError_(thrown)) {
return fail(function() { return 'Expected function to throw an Error, but it threw ' + j$.pp(thrown) + '.'; }); return fail(function() { return 'Expected function to throw an Error, but it threw ' + matchersUtil.pp(thrown) + '.'; });
} }
return errorMatcher.match(thrown); return errorMatcher.match(thrown);
@@ -97,7 +97,7 @@ getJasmineRequireObj().toThrowError = function(j$) {
thrownMessage = ''; thrownMessage = '';
if (expected) { if (expected) {
thrownMessage = ' with message ' + j$.pp(thrown.message); thrownMessage = ' with message ' + matchersUtil.pp(thrown.message);
} }
return thrownName + thrownMessage; return thrownName + thrownMessage;
@@ -107,9 +107,9 @@ getJasmineRequireObj().toThrowError = function(j$) {
if (expected === null) { if (expected === null) {
return ''; return '';
} else if (expected instanceof RegExp) { } else if (expected instanceof RegExp) {
return ' with a message matching ' + j$.pp(expected); return ' with a message matching ' + matchersUtil.pp(expected);
} else { } else {
return ' with message ' + j$.pp(expected); return ' with message ' + matchersUtil.pp(expected);
} }
} }
+8 -8
View File
@@ -10,7 +10,7 @@ getJasmineRequireObj().toThrowMatching = function(j$) {
* @example * @example
* expect(function() { throw new Error('nope'); }).toThrowMatching(function(thrown) { return thrown.message === 'nope'; }); * expect(function() { throw new Error('nope'); }).toThrowMatching(function(thrown) { return thrown.message === 'nope'; });
*/ */
function toThrowMatching() { function toThrowMatching(matchersUtil) {
return { return {
compare: function(actual, predicate) { compare: function(actual, predicate) {
var thrown; var thrown;
@@ -40,14 +40,14 @@ getJasmineRequireObj().toThrowMatching = function(j$) {
} }
} }
}; };
}
function thrownDescription(thrown) { function thrownDescription(thrown) {
if (thrown && thrown.constructor) { if (thrown && thrown.constructor) {
return j$.fnNameFor(thrown.constructor) + ' with message ' + return j$.fnNameFor(thrown.constructor) + ' with message ' +
j$.pp(thrown.message); matchersUtil.pp(thrown.message);
} else { } else {
return j$.pp(thrown); return matchersUtil.pp(thrown);
}
} }
} }
+6 -2
View File
@@ -54,15 +54,19 @@ var getJasmineRequireObj = (function(jasmineGlobal) {
j$.asymmetricEqualityTesterArgCompatShim = jRequire.asymmetricEqualityTesterArgCompatShim( j$.asymmetricEqualityTesterArgCompatShim = jRequire.asymmetricEqualityTesterArgCompatShim(
j$ j$
); );
j$.makePrettyPrinter = jRequire.makePrettyPrinter(j$);
j$.pp = j$.makePrettyPrinter();
j$.MatchersUtil = jRequire.MatchersUtil(j$); j$.MatchersUtil = jRequire.MatchersUtil(j$);
j$.matchersUtil = new j$.MatchersUtil({ customTesters: [] }); j$.matchersUtil = new j$.MatchersUtil({
customTesters: [],
pp: j$.pp
});
j$.ObjectContaining = jRequire.ObjectContaining(j$); j$.ObjectContaining = jRequire.ObjectContaining(j$);
j$.ArrayContaining = jRequire.ArrayContaining(j$); j$.ArrayContaining = jRequire.ArrayContaining(j$);
j$.ArrayWithExactContents = jRequire.ArrayWithExactContents(j$); j$.ArrayWithExactContents = jRequire.ArrayWithExactContents(j$);
j$.MapContaining = jRequire.MapContaining(j$); j$.MapContaining = jRequire.MapContaining(j$);
j$.SetContaining = jRequire.SetContaining(j$); j$.SetContaining = jRequire.SetContaining(j$);
j$.pp = jRequire.pp(j$);
j$.QueueRunner = jRequire.QueueRunner(j$); j$.QueueRunner = jRequire.QueueRunner(j$);
j$.ReportDispatcher = jRequire.ReportDispatcher(j$); j$.ReportDispatcher = jRequire.ReportDispatcher(j$);
j$.Spec = jRequire.Spec(j$); j$.Spec = jRequire.Spec(j$);