diff --git a/lib/jasmine-core/jasmine.js b/lib/jasmine-core/jasmine.js index 999cd0fb..b6bd9040 100644 --- a/lib/jasmine-core/jasmine.js +++ b/lib/jasmine-core/jasmine.js @@ -59,8 +59,9 @@ var getJasmineRequireObj = (function (jasmineGlobal) { j$.Env = jRequire.Env(j$); j$.StackTrace = jRequire.StackTrace(j$); j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); - j$.Expectation = jRequire.Expectation(); - j$.AsyncExpectation = jRequire.AsyncExpectation(j$); + j$.ExpectationFilterChain = jRequire.ExpectationFilterChain(); + j$.Expector = jRequire.Expector(j$); + j$.Expectation = jRequire.Expectation(j$); j$.buildExpectationResult = jRequire.buildExpectationResult(); j$.JsApiReporter = jRequire.JsApiReporter(); j$.matchersUtil = jRequire.matchersUtil(j$); @@ -93,6 +94,7 @@ var getJasmineRequireObj = (function (jasmineGlobal) { j$.NotEmpty = jRequire.NotEmpty(j$); j$.matchers = jRequire.requireMatchers(jRequire, j$); + j$.asyncMatchers = jRequire.requireAsyncMatchers(jRequire, j$); return j$; }; @@ -968,6 +970,7 @@ getJasmineRequireObj().Env = function(j$) { }; j$.Expectation.addCoreMatchers(j$.matchers); + j$.Expectation.addAsyncCoreMatchers(j$.asyncMatchers); var nextSpecId = 0; var getNextSpecId = function() { @@ -980,7 +983,7 @@ getJasmineRequireObj().Env = function(j$) { }; var expectationFactory = function(actual, spec) { - return j$.Expectation.Factory({ + return j$.Expectation.factory({ util: j$.matchersUtil, customEqualityTesters: runnableResources[spec.id].customEqualityTesters, customMatchers: runnableResources[spec.id].customMatchers, @@ -994,7 +997,7 @@ getJasmineRequireObj().Env = function(j$) { }; var asyncExpectationFactory = function(actual, spec) { - return j$.AsyncExpectation.factory({ + return j$.Expectation.asyncFactory({ util: j$.matchersUtil, customEqualityTesters: runnableResources[spec.id].customEqualityTesters, actual: actual, @@ -2143,203 +2146,6 @@ getJasmineRequireObj().Truthy = function(j$) { return Truthy; }; -getJasmineRequireObj().AsyncExpectation = function(j$) { - var promiseForMessage = { - jasmineToString: function() { return 'a promise'; } - }; - - /** - * Asynchronous matchers. - * @namespace async-matchers - */ - function AsyncExpectation(options) { - var global = options.global || j$.getGlobal(); - this.util = options.util || { buildFailureMessage: function() {} }; - this.customEqualityTesters = options.customEqualityTesters || []; - this.addExpectationResult = options.addExpectationResult || function(){}; - this.actual = options.actual; - this.isNot = options.isNot; - - if (!global.Promise) { - throw new Error('expectAsync is unavailable because the environment does not support promises.'); - } - - if (!j$.isPromiseLike(this.actual)) { - throw new Error('Expected expectAsync to be called with a promise.'); - } - - ['toBeResolved', 'toBeRejected', 'toBeResolvedTo', 'toBeRejectedWith'].forEach(wrapCompare.bind(this)); - } - - function wrapCompare(name) { - var compare = this[name]; - this[name] = function() { - var self = this; - var args = Array.prototype.slice.call(arguments); - args.unshift(this.actual); - - // Capture the call stack here, before we go async, so that it will - // contain frames that are relevant to the user instead of just parts - // of Jasmine. - var errorForStack = j$.util.errorWithStack(); - - return compare.apply(self, args).then(function(result) { - var message; - - if (self.isNot) { - result.pass = !result.pass; - } - - args[0] = promiseForMessage; - message = j$.Expectation.finalizeMessage(self.util, name, self.isNot, args, result); - - self.addExpectationResult(result.pass, { - matcherName: name, - passed: result.pass, - message: message, - error: undefined, - errorForStack: errorForStack, - actual: self.actual - }); - }); - }; - } - - /** - * Expect a promise to be resolved. - * @function - * @async - * @name async-matchers#toBeResolved - * @example - * await expectAsync(aPromise).toBeResolved(); - * @example - * return expectAsync(aPromise).toBeResolved(); - */ - AsyncExpectation.prototype.toBeResolved = function(actual) { - return actual.then( - function() { return {pass: true}; }, - function() { return {pass: false}; } - ); - }; - - /** - * Expect a promise to be rejected. - * @function - * @async - * @name async-matchers#toBeRejected - * @example - * await expectAsync(aPromise).toBeRejected(); - * @example - * return expectAsync(aPromise).toBeRejected(); - */ - AsyncExpectation.prototype.toBeRejected = function(actual) { - return actual.then( - function() { return {pass: false}; }, - function() { return {pass: true}; } - ); - }; - - /** - * Expect a promise to be resolved to a value equal to the expected, using deep equality comparison. - * @function - * @async - * @name async-matchers#toBeResolvedTo - * @param {Object} expected - Value that the promise is expected to resolve to - * @example - * await expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); - * @example - * return expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); - */ - AsyncExpectation.prototype.toBeResolvedTo = function(actualPromise, expectedValue) { - var self = this; - - function prefix(passed) { - return 'Expected a promise ' + - (passed ? 'not ' : '') + - 'to be resolved to ' + j$.pp(expectedValue); - } - - return actualPromise.then( - function(actualValue) { - if (self.util.equals(actualValue, expectedValue, self.customEqualityTesters)) { - return { - pass: true, - message: prefix(true) + '.' - }; - } else { - return { - pass: false, - message: prefix(false) + ' but it was resolved to ' + j$.pp(actualValue) + '.' - }; - } - }, - function() { - return { - pass: false, - message: prefix(false) + ' but it was rejected.' - }; - } - ); - }; - - /** - * Expect a promise to be rejected to a value equal to the expected, using deep equality comparison. - * @function - * @async - * @name async-matchers#toBeRejectedWith - * @param {Object} expected - Value that the promise is expected to reject to - * @example - * await expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); - * @example - * return expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); - */ - AsyncExpectation.prototype.toBeRejectedWith = function(actualPromise, expectedValue) { - var self = this; - - function prefix(passed) { - return 'Expected a promise ' + - (passed ? 'not ' : '') + - 'to be rejected to ' + j$.pp(expectedValue); - } - - return actualPromise.then( - function() { - return { - pass: false, - message: prefix(false) + ' but it was resolved.' - }; - }, - function(actualValue) { - if (self.util.equals(actualValue, expectedValue, self.customEqualityTesters)) { - return { - pass: true, - message: prefix(true) + '.' - }; - } else { - return { - pass: false, - message: prefix(false) + ' but it was rejected to ' + j$.pp(actualValue) + '.' - }; - } - } - ); - }; - - - AsyncExpectation.factory = function(options) { - var expect = new AsyncExpectation(options); - - options = j$.util.clone(options); - options.isNot = true; - expect.not = new AsyncExpectation(options); - - return expect; - }; - - - return AsyncExpectation; -}; - getJasmineRequireObj().CallTracker = function(j$) { /** @@ -2977,107 +2783,206 @@ getJasmineRequireObj().ExceptionFormatter = function(j$) { return ExceptionFormatter; }; -getJasmineRequireObj().Expectation = function() { +getJasmineRequireObj().Expectation = function(j$) { + var promiseForMessage = { + jasmineToString: function() { return 'a promise'; } + }; /** * Matchers that come with Jasmine out of the box. * @namespace matchers */ function Expectation(options) { - this.util = options.util || { buildFailureMessage: function() {} }; - this.customEqualityTesters = options.customEqualityTesters || []; - this.actual = options.actual; - this.addExpectationResult = options.addExpectationResult || function(){}; - this.isNot = options.isNot; + this.expector = new j$.Expector(options); var customMatchers = options.customMatchers || {}; for (var matcherName in customMatchers) { - this[matcherName] = Expectation.prototype.wrapCompare(matcherName, customMatchers[matcherName]); + this[matcherName] = wrapSyncCompare(matcherName, customMatchers[matcherName]); } } - Expectation.prototype.wrapCompare = function(name, matcherFactory) { - return function() { - var args = Array.prototype.slice.call(arguments, 0), - expected = args.slice(0), - message; - - args.unshift(this.actual); - - var matcher = matcherFactory(this.util, this.customEqualityTesters), - matcherCompare = matcher.compare; - - function defaultNegativeCompare() { - var result = matcher.compare.apply(null, args); - result.pass = !result.pass; - return result; - } - - if (this.isNot) { - matcherCompare = matcher.negativeCompare || defaultNegativeCompare; - } - - var result = matcherCompare.apply(null, args); - message = Expectation.finalizeMessage(this.util, name, this.isNot, args, result); - - if (expected.length == 1) { - expected = expected[0]; - } - - // TODO: how many of these params are needed? - this.addExpectationResult( - result.pass, - { - matcherName: name, - passed: result.pass, - message: message, - error: result.error, - actual: this.actual, - expected: expected // TODO: this may need to be arrayified/sliced - } - ); - }; + Expectation.prototype.withContext = function withContext(message) { + return addFilter(this, new ContextAddingFilter(message)); }; - Expectation.finalizeMessage = function(util, name, isNot, args, result) { - if (result.pass) { - return ''; - } else if (result.message) { - if (Object.prototype.toString.apply(result.message) === '[object Function]') { + Object.defineProperty(Expectation.prototype, 'not', { + get: function() { + return addFilter(this, syncNegatingFilter); + } + }); + + /** + * Asynchronous matchers. + * @namespace async-matchers + */ + function AsyncExpectation(options) { + var global = options.global || j$.getGlobal(); + this.expector = new j$.Expector(options); + + if (!global.Promise) { + throw new Error('expectAsync is unavailable because the environment does not support promises.'); + } + + if (!j$.isPromiseLike(this.expector.actual)) { + throw new Error('Expected expectAsync to be called with a promise.'); + } + } + + AsyncExpectation.prototype.withContext = function withContext(message) { + return addFilter(this, new ContextAddingFilter(message)); + }; + + Object.defineProperty(AsyncExpectation.prototype, 'not', { + get: function() { + return addFilter(this, asyncNegatingFilter); + } + }); + + function wrapSyncCompare(name, matcherFactory) { + return function() { + var result = this.expector.compare(name, matcherFactory, arguments); + this.expector.processResult(result); + }; + } + + function wrapAsyncCompare(name, matcherFactory) { + return function() { + var self = this; + + // Capture the call stack here, before we go async, so that it will contain + // frames that are relevant to the user instead of just parts of Jasmine. + var errorForStack = j$.util.errorWithStack(); + + return this.expector.compare(name, matcherFactory, arguments).then(function(result) { + self.expector.processResult(result, errorForStack, promiseForMessage); + }); + }; + } + + function addCoreMatchers(prototype, matchers, wrapper) { + for (var matcherName in matchers) { + var matcher = matchers[matcherName]; + prototype[matcherName] = wrapper(matcherName, matcher); + } + } + + function addFilter(source, filter) { + var result = Object.create(source); + result.expector = source.expector.addFilter(filter); + return result; + } + + function negatedFailureMessage(result, matcherName, args, util) { + if (result.message) { + if (j$.isFunction_(result.message)) { return result.message(); } else { return result.message; } - } else { - args = args.slice(); - args.unshift(isNot); - args.unshift(name); - return util.buildFailureMessage.apply(null, args); + } + + args = args.slice(); + args.unshift(true); + args.unshift(matcherName); + return util.buildFailureMessage.apply(null, args); + } + + function negate(result) { + result.pass = !result.pass; + return result; + } + + var syncNegatingFilter = { + selectComparisonFunc: function(matcher) { + function defaultNegativeCompare() { + return negate(matcher.compare.apply(null, arguments)); + } + + return matcher.negativeCompare || defaultNegativeCompare; + }, + buildFailureMessage: negatedFailureMessage + }; + + var asyncNegatingFilter = { + selectComparisonFunc: function(matcher) { + function defaultNegativeCompare() { + return matcher.compare.apply(this, arguments).then(negate); + } + + return defaultNegativeCompare; + }, + buildFailureMessage: negatedFailureMessage + }; + + function ContextAddingFilter(message) { + this.message = message; + } + + ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { + return this.message + ': ' + msg; + }; + + return { + factory: function(options) { + return new Expectation(options || {}); + }, + addCoreMatchers: function(matchers) { + addCoreMatchers(Expectation.prototype, matchers, wrapSyncCompare); + }, + asyncFactory: function(options) { + return new AsyncExpectation(options || {}); + }, + addAsyncCoreMatchers: function(matchers) { + addCoreMatchers(AsyncExpectation.prototype, matchers, wrapAsyncCompare); } }; +}; - Expectation.addCoreMatchers = function(matchers) { - var prototype = Expectation.prototype; - for (var matcherName in matchers) { - var matcher = matchers[matcherName]; - prototype[matcherName] = prototype.wrapCompare(matcherName, matcher); +getJasmineRequireObj().ExpectationFilterChain = function() { + function ExpectationFilterChain(maybeFilter, prev) { + this.filter_ = maybeFilter; + this.prev_ = prev; + } + + ExpectationFilterChain.prototype.addFilter = function(filter) { + return new ExpectationFilterChain(filter, this); + }; + + ExpectationFilterChain.prototype.selectComparisonFunc = function(matcher) { + return this.callFirst_('selectComparisonFunc', arguments).result; + }; + + ExpectationFilterChain.prototype.buildFailureMessage = function(result, matcherName, args, util) { + return this.callFirst_('buildFailureMessage', arguments).result; + }; + + ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { + var result = this.callFirst_('modifyFailureMessage', arguments).result; + return result || msg; + }; + + ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { + var prevResult; + + if (this.prev_) { + prevResult = this.prev_.callFirst_(fname, args); + + if (prevResult.found) { + return prevResult; + } } + + if (this.filter_ && this.filter_[fname]) { + return { + found: true, + result: this.filter_[fname].apply(this.filter_, args) + }; + } + + return {found: false}; }; - Expectation.Factory = function(options) { - options = options || {}; - - var expect = new Expectation(options); - - // TODO: this would be nice as its own Object - NegativeExpectation - // TODO: copy instead of mutate options - options.isNot = true; - expect.not = new Expectation(options); - - return expect; - }; - - return Expectation; + return ExpectationFilterChain; }; //TODO: expectation result may make more sense as a presentation of an expectation. @@ -3146,6 +3051,87 @@ getJasmineRequireObj().buildExpectationResult = function() { return buildExpectationResult; }; +getJasmineRequireObj().Expector = function(j$) { + function Expector(options) { + this.util = options.util || { buildFailureMessage: function() {} }; + this.customEqualityTesters = options.customEqualityTesters || []; + this.actual = options.actual; + this.addExpectationResult = options.addExpectationResult || function(){}; + this.filters = new j$.ExpectationFilterChain(); + } + + Expector.prototype.instantiateMatcher = function(matcherName, matcherFactory, args) { + this.matcherName = matcherName; + this.args = Array.prototype.slice.call(args, 0); + this.expected = this.args.slice(0); + + this.args.unshift(this.actual); + + var matcher = matcherFactory(this.util, this.customEqualityTesters); + var comparisonFunc = this.filters.selectComparisonFunc(matcher); + return comparisonFunc || matcher.compare; + }; + + Expector.prototype.buildMessage = function(result) { + var self = this; + + if (result.pass) { + return ''; + } + + var msg = this.filters.buildFailureMessage(result, this.matcherName, this.args, this.util, defaultMessage); + return this.filters.modifyFailureMessage(msg || defaultMessage()); + + function defaultMessage() { + if (!result.message) { + var args = self.args.slice(); + args.unshift(false); + args.unshift(self.matcherName); + return self.util.buildFailureMessage.apply(null, args); + } else if (j$.isFunction_(result.message)) { + return result.message(); + } else { + return result.message; + } + } + }; + + Expector.prototype.compare = function(matcherName, matcherFactory, args) { + var matcherCompare = this.instantiateMatcher(matcherName, matcherFactory, args); + return matcherCompare.apply(null, this.args); + }; + + Expector.prototype.addFilter = function(filter) { + var result = Object.create(this); + result.filters = this.filters.addFilter(filter); + return result; + }; + + Expector.prototype.processResult = function(result, errorForStack, actualOverride) { + this.args[0] = actualOverride || this.args[0]; + var message = this.buildMessage(result); + + if (this.expected.length === 1) { + this.expected = this.expected[0]; + } + + this.addExpectationResult( + result.pass, + { + matcherName: this.matcherName, + passed: result.pass, + message: message, + error: errorForStack ? undefined : result.error, + errorForStack: errorForStack || undefined, + actual: this.actual, + expected: this.expected // TODO: this may need to be arrayified/sliced + } + ); + }; + + return Expector; +}; + getJasmineRequireObj().formatErrorMsg = function() { function generateErrorMsg(domain, usage) { var usageDefinition = usage ? '\nUsage: ' + usage : ''; @@ -3218,6 +3204,146 @@ getJasmineRequireObj().GlobalErrors = function(j$) { return GlobalErrors; }; +getJasmineRequireObj().toBeRejected = function(j$) { + /** + * Expect a promise to be rejected. + * @function + * @async + * @name async-matchers#toBeRejected + * @example + * await expectAsync(aPromise).toBeRejected(); + * @example + * return expectAsync(aPromise).toBeRejected(); + */ + return function toBeResolved(util) { + return { + compare: function(actual) { + return actual.then( + function() { return {pass: false}; }, + function() { return {pass: true}; } + ); + } + }; + }; +}; + +getJasmineRequireObj().toBeRejectedWith = function(j$) { + /** + * Expect a promise to be rejected with a value equal to the expected, using deep equality comparison. + * @function + * @async + * @name async-matchers#toBeRejectedWith + * @param {Object} expected - Value that the promise is expected to be rejected with + * @example + * await expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); + * @example + * return expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); + */ + return function toBeRejectedWith(util, customEqualityTesters) { + return { + compare: function(actualPromise, expectedValue) { + function prefix(passed) { + return 'Expected a promise ' + + (passed ? 'not ' : '') + + 'to be rejected with ' + j$.pp(expectedValue); + } + + return actualPromise.then( + function() { + return { + pass: false, + message: prefix(false) + ' but it was resolved.' + }; + }, + function(actualValue) { + if (util.equals(actualValue, expectedValue, customEqualityTesters)) { + return { + pass: true, + message: prefix(true) + '.' + }; + } else { + return { + pass: false, + message: prefix(false) + ' but it was rejected with ' + j$.pp(actualValue) + '.' + }; + } + } + ); + } + }; + }; +}; + +getJasmineRequireObj().toBeResolved = function(j$) { + /** + * Expect a promise to be resolved. + * @function + * @async + * @name async-matchers#toBeResolved + * @example + * await expectAsync(aPromise).toBeResolved(); + * @example + * return expectAsync(aPromise).toBeResolved(); + */ + return function toBeResolved(util) { + return { + compare: function(actual) { + return actual.then( + function() { return {pass: true}; }, + function() { return {pass: false}; } + ); + } + }; + }; +}; + +getJasmineRequireObj().toBeResolvedTo = function(j$) { + /** + * Expect a promise to be resolved to a value equal to the expected, using deep equality comparison. + * @function + * @async + * @name async-matchers#toBeResolvedTo + * @param {Object} expected - Value that the promise is expected to resolve to + * @example + * await expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); + * @example + * return expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); + */ + return function toBeResolvedTo(util, customEqualityTesters) { + return { + compare: function(actualPromise, expectedValue) { + function prefix(passed) { + return 'Expected a promise ' + + (passed ? 'not ' : '') + + 'to be resolved to ' + j$.pp(expectedValue); + } + + return actualPromise.then( + function(actualValue) { + if (util.equals(actualValue, expectedValue, customEqualityTesters)) { + return { + pass: true, + message: prefix(true) + '.' + }; + } else { + return { + pass: false, + message: prefix(false) + ' but it was resolved to ' + j$.pp(actualValue) + '.' + }; + } + }, + function() { + return { + pass: false, + message: prefix(false) + ' but it was rejected.' + }; + } + ); + } + }; + }; +}; + getJasmineRequireObj().DiffBuilder = function(j$) { return function DiffBuilder() { var path = new j$.ObjectPath(), @@ -3808,6 +3934,23 @@ getJasmineRequireObj().ObjectPath = function(j$) { return ObjectPath; }; +getJasmineRequireObj().requireAsyncMatchers = function(jRequire, j$) { + var availableMatchers = [ + 'toBeResolved', + 'toBeRejected', + 'toBeResolvedTo', + 'toBeRejectedWith' + ], + matchers = {}; + + for (var i = 0; i < availableMatchers.length; i++) { + var name = availableMatchers[i]; + matchers[name] = jRequire[name](j$); + } + + return matchers; +}; + getJasmineRequireObj().toBe = function(j$) { /** * {@link expect} the actual value to be `===` to the expected value. diff --git a/spec/core/AsyncExpectationSpec.js b/spec/core/AsyncExpectationSpec.js index d53930a6..906b3081 100644 --- a/spec/core/AsyncExpectationSpec.js +++ b/spec/core/AsyncExpectationSpec.js @@ -1,337 +1,32 @@ describe('AsyncExpectation', function() { + beforeEach(function() { + jasmineUnderTest.Expectation.addAsyncCoreMatchers(jasmineUnderTest.asyncMatchers); + }); + describe('Factory', function() { it('throws an Error if promises are not available', function() { var thenable = {then: function() {}}, options = {global: {}, actual: thenable} - function f() { jasmineUnderTest.AsyncExpectation.factory(options); } + function f() { jasmineUnderTest.Expectation.asyncFactory(options); } expect(f).toThrowError('expectAsync is unavailable because the environment does not support promises.'); }); it('throws an Error if the argument is not a promise', function() { jasmine.getEnv().requirePromises(); function f() { - jasmineUnderTest.AsyncExpectation.factory({actual: 'not a promise'}); + jasmineUnderTest.Expectation.asyncFactory({actual: 'not a promise'}); } expect(f).toThrowError('Expected expectAsync to be called with a promise.'); }); }); - describe('#toBeResolved', function() { - it('passes if the actual is resolved', function() { - jasmine.getEnv().requirePromises(); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - actual = Promise.resolve(), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - actual: actual, - addExpectationResult: addExpectationResult - }); - - return expectation.toBeResolved().then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(true, { - matcherName: 'toBeResolved', - passed: true, - message: '', - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - }); - - it('fails if the actual is rejected', function() { - jasmine.getEnv().requirePromises(); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - actual = Promise.reject('AsyncExpectationSpec rejection'), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - actual: actual, - addExpectationResult: addExpectationResult - }); - - return expectation.toBeResolved().then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: 'toBeResolved', - passed: false, - message: 'Expected a promise to be resolved.', - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - }); - }); - - describe('#toBeRejected', function() { - it('passes if the actual is rejected', function() { - jasmine.getEnv().requirePromises(); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - actual = Promise.reject('AsyncExpectationSpec rejection'), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - actual: actual, - addExpectationResult: addExpectationResult - }); - - return expectation.toBeRejected().then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(true, { - matcherName: 'toBeRejected', - passed: true, - message: '', - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - }); - - it('fails if the actual is resolved', function() { - jasmine.getEnv().requirePromises(); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - actual = Promise.resolve(), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - actual: actual, - addExpectationResult: addExpectationResult - }); - - return expectation.toBeRejected().then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: 'toBeRejected', - passed: false, - message: 'Expected a promise to be rejected.', - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - }); - }); - - describe('#toBeRejectedWith', function () { - it('should return true if the promise is rejected to the expected value', function () { - jasmine.getEnv().requirePromises(); - - var actual = Promise.reject({error: 'PEBCAK'}); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - actual: actual, - addExpectationResult: addExpectationResult - }); - - return expectation.toBeRejectedWith({error: 'PEBCAK'}).then(function () { - expect(addExpectationResult).toHaveBeenCalledWith(true, { - matcherName: 'toBeRejectedWith', - passed: true, - message: '', - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - - }); - - it('should fail if the promise resolves', function () { - jasmine.getEnv().requirePromises(); - - var actual = Promise.resolve('AsyncExpectation error'); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - actual: actual, - addExpectationResult: addExpectationResult - }); - - return expectation.toBeRejectedWith('').then(function () { - expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: 'toBeRejectedWith', - passed: false, - message: "Expected a promise to be rejected to '' but it was resolved.", - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - }); - - it('should fail if the promise is rejected to a different value', function () { - jasmine.getEnv().requirePromises(); - - var actual = Promise.reject('A Bad Apple'); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - actual: actual, - addExpectationResult: addExpectationResult - }); - - return expectation.toBeRejectedWith('Some Cool Thing').then(function () { - expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: 'toBeRejectedWith', - passed: false, - message: "Expected a promise to be rejected to 'Some Cool Thing' but it was rejected to 'A Bad Apple'.", - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - }); - - it('should build its error correctly when negated', function () { - jasmine.getEnv().requirePromises(); - - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = jasmineUnderTest.AsyncExpectation.factory({ - util: jasmineUnderTest.matchersUtil, - actual: Promise.reject(true), - addExpectationResult: addExpectationResult - }); - - return expectation.not.toBeRejectedWith(true).then(function () { - expect(addExpectationResult).toHaveBeenCalledWith(false, - jasmine.objectContaining({ - passed: false, - message: 'Expected a promise not to be rejected to true.' - }) - ); - }); - }); - - it('should support custom equality testers', function () { - jasmine.getEnv().requirePromises(); - - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - customEqualityTesters: [function() { return true; }], - actual: Promise.reject('actual'), - addExpectationResult: addExpectationResult - }); - - return expectation.toBeRejectedWith('expected').then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(true, - jasmine.objectContaining({passed: true})); - }); - }); - }); - - describe('#toBeResolvedTo', function() { - it('passes if the promise is resolved to the expected value', function() { - jasmine.getEnv().requirePromises(); - - var actual = Promise.resolve({foo: 42}); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - actual: actual, - addExpectationResult: addExpectationResult - }); - - return expectation.toBeResolvedTo({foo: 42}).then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(true, { - matcherName: 'toBeResolvedTo', - passed: true, - message: '', - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - }); - - it('fails if the promise is rejected', function() { - jasmine.getEnv().requirePromises(); - - var actual = Promise.reject('AsyncExpectationSpec error'); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - actual: actual, - addExpectationResult: addExpectationResult - }); - - return expectation.toBeResolvedTo('').then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: 'toBeResolvedTo', - passed: false, - message: "Expected a promise to be resolved to '' but it was rejected.", - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - }); - - it('fails if the promise is resolved to a different value', function() { - jasmine.getEnv().requirePromises(); - - var actual = Promise.resolve({foo: 17}); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - actual: actual, - addExpectationResult: addExpectationResult - }); - - return expectation.toBeResolvedTo({foo: 42}).then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, { - matcherName: 'toBeResolvedTo', - passed: false, - message: 'Expected a promise to be resolved to Object({ foo: 42 }) but it was resolved to Object({ foo: 17 }).', - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - }); - - it('builds its message correctly when negated', function() { - jasmine.getEnv().requirePromises(); - - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = jasmineUnderTest.AsyncExpectation.factory({ - util: jasmineUnderTest.matchersUtil, - actual: Promise.resolve(true), - addExpectationResult: addExpectationResult - }); - - return expectation.not.toBeResolvedTo(true).then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(false, - jasmine.objectContaining({ - passed: false, - message: 'Expected a promise not to be resolved to true.' - }) - ); - }); - }); - - it('supports custom equality testers', function() { - jasmine.getEnv().requirePromises(); - - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = new jasmineUnderTest.AsyncExpectation({ - util: jasmineUnderTest.matchersUtil, - customEqualityTesters: [function() { return true; }], - actual: Promise.resolve('actual'), - addExpectationResult: addExpectationResult - }); - - return expectation.toBeResolvedTo('expected').then(function() { - expect(addExpectationResult).toHaveBeenCalledWith(true, - jasmine.objectContaining({passed: true})); - }); - }); - }); - describe('#not', function() { it('converts a pass to a fail', function() { jasmine.getEnv().requirePromises(); var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.resolve(), - expectation = jasmineUnderTest.AsyncExpectation.factory({ + expectation = jasmineUnderTest.Expectation.asyncFactory({ util: jasmineUnderTest.matchersUtil, actual: actual, addExpectationResult: addExpectationResult @@ -352,7 +47,7 @@ describe('AsyncExpectation', function() { var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.reject(), - expectation = jasmineUnderTest.AsyncExpectation.factory({ + expectation = jasmineUnderTest.Expectation.asyncFactory({ util: jasmineUnderTest.matchersUtil, actual: actual, addExpectationResult: addExpectationResult @@ -371,18 +66,19 @@ describe('AsyncExpectation', function() { it('propagates rejections from the comparison function', function() { jasmine.getEnv().requirePromises(); - var error = new Error('AsyncExpectationSpec failure'); + var error = new Error('ExpectationSpec failure'); - spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') - .and.returnValue(Promise.reject(error)); var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = dummyPromise(), - expectation = new jasmineUnderTest.AsyncExpectation({ + expectation = jasmineUnderTest.Expectation.asyncFactory({ actual: actual, addExpectationResult: addExpectationResult }); + spyOn(expectation, 'toBeResolved') + .and.returnValue(Promise.reject(error)); + return expectation.toBeResolved() .then( function() { fail('Expected a rejection'); }, @@ -390,6 +86,121 @@ describe('AsyncExpectation', function() { ); }); + describe('#withContext', function() { + it("prepends the context to the generated failure message", function() { + jasmine.getEnv().requirePromises(); + + var util = { + buildFailureMessage: function() { return 'failure message'; } + }, + addExpectationResult = jasmine.createSpy('addExpectationResult'), + expectation = jasmineUnderTest.Expectation.asyncFactory({ + actual: Promise.reject('rejected'), + addExpectationResult: addExpectationResult, + util: util + }); + + return expectation.withContext('Some context').toBeResolved() + .then( + function() { + expect(addExpectationResult).toHaveBeenCalledWith(false, + jasmine.objectContaining({ + message: 'Some context: failure message' + })); + }); + }); + + it("prepends the context to a custom failure message", function() { + jasmine.getEnv().requirePromises(); + + var util = { + buildFailureMessage: function() { return 'failure message'; } + }, + addExpectationResult = jasmine.createSpy('addExpectationResult'), + expectation = jasmineUnderTest.Expectation.asyncFactory({ + actual: Promise.reject('b'), + addExpectationResult: addExpectationResult, + util: util + }); + + return expectation.withContext('Some context').toBeResolvedTo('a') + .then( + function() { + expect(addExpectationResult).toHaveBeenCalledWith(false, + jasmine.objectContaining({ + message: "Some context: Expected a promise to be resolved to 'a' but it was rejected." + })); + }); + }); + + it("prepends the context to a custom failure message from a function", function() { + pending('should actually work, but no custom matchers for async yet'); + jasmine.getEnv().requirePromises(); + + var util = { + buildFailureMessage: function() { return 'failure message'; } + }, + addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = Promise.reject(), + expectation = jasmineUnderTest.Expectation.asyncFactory({ + actual: actual, + addExpectationResult: addExpectationResult, + util: util + }); + + return expectation.withContext('Some context').toBeResolved() + .then( + function() { + expect(addExpectationResult).toHaveBeenCalledWith(false, + jasmine.objectContaining({ + message: 'Some context: msg' + })); + }); + }); + + it("works with #not", function() { + jasmine.getEnv().requirePromises(); + + var addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = Promise.resolve(), + expectation = jasmineUnderTest.Expectation.asyncFactory({ + actual: actual, + addExpectationResult: addExpectationResult, + util: jasmineUnderTest.matchersUtil + }); + + return expectation.withContext('Some context').not.toBeResolved() + .then( + function() { + expect(addExpectationResult).toHaveBeenCalledWith(false, + jasmine.objectContaining({ + message: 'Some context: Expected a promise not to be resolved.' + })); + }); + }); + + it("works with #not and a custom message", function() { + jasmine.getEnv().requirePromises(); + + var addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = Promise.resolve('a'), + expectation = jasmineUnderTest.Expectation.asyncFactory({ + actual: actual, + addExpectationResult: addExpectationResult, + util: jasmineUnderTest.matchersUtil + }); + + return expectation.withContext('Some context').not.toBeResolvedTo('a') + .then( + function() { + expect(addExpectationResult).toHaveBeenCalledWith(false, + jasmine.objectContaining({ + message: "Some context: Expected a promise not to be resolved to 'a'." + })); + }); + }); + }); + function dummyPromise() { return new Promise(function(resolve, reject) { }); diff --git a/spec/core/ExpectationFilterChainSpec.js b/spec/core/ExpectationFilterChainSpec.js new file mode 100644 index 00000000..195fbe27 --- /dev/null +++ b/spec/core/ExpectationFilterChainSpec.js @@ -0,0 +1,113 @@ +describe('ExpectationFilterChain', function() { + describe('#addFilter', function() { + it('returns a new filter chain with the added filter', function() { + var first = jasmine.createSpy('first'), + second = jasmine.createSpy('second'), + orig = new jasmineUnderTest.ExpectationFilterChain({ + modifyFailureMessage: first + }), + added = orig.addFilter({selectComparisonFunc: second}); + + added.modifyFailureMessage(); + expect(first).toHaveBeenCalled(); + added.selectComparisonFunc(); + expect(second).toHaveBeenCalled(); + }); + + it('does not modify the original filter chain', function() { + var orig = new jasmineUnderTest.ExpectationFilterChain({}), + f = jasmine.createSpy('f'); + + orig.addFilter({selectComparisonFunc: f}); + + orig.selectComparisonFunc(); + expect(f).not.toHaveBeenCalled(); + }); + }); + + describe('#selectComparisonFunc', function() { + describe('When no filters have #selectComparisonFunc', function() { + it('returns undefined', function() { + var chain = new jasmineUnderTest.ExpectationFilterChain(); + chain.addFilter({}); + expect(chain.selectComparisonFunc()).toBeUndefined(); + }); + }); + + describe('When some filters have #selectComparisonFunc', function() { + it('calls the first filter that has #selectComparisonFunc', function() { + var first = jasmine.createSpy('first').and.returnValue('first'), + second = jasmine.createSpy('second').and.returnValue('second'), + chain = new jasmineUnderTest.ExpectationFilterChain() + .addFilter({selectComparisonFunc: first}) + .addFilter({selectComparisonFunc: second}), + matcher = {}, + result; + + result = chain.selectComparisonFunc(matcher); + + expect(first).toHaveBeenCalledWith(matcher); + expect(second).not.toHaveBeenCalled(); + expect(result).toEqual('first'); + }); + }); + }); + + describe('#buildFailureMessage', function() { + describe('When no filters have #buildFailureMessage', function() { + it('returns undefined', function() { + var chain = new jasmineUnderTest.ExpectationFilterChain(); + chain.addFilter({}); + expect(chain.buildFailureMessage()).toBeUndefined(); + }); + }); + + describe('When some filters have #buildFailureMessage', function() { + it('calls the first filter that has #buildFailureMessage', function() { + var first = jasmine.createSpy('first').and.returnValue('first'), + second = jasmine.createSpy('second').and.returnValue('second'), + chain = new jasmineUnderTest.ExpectationFilterChain() + .addFilter({buildFailureMessage: first}) + .addFilter({buildFailureMessage: second}), + matcherResult = {pass: false}, + matcherName = 'foo', + args = [], + util = {}, + result; + + result = chain.buildFailureMessage(matcherResult, matcherName, args, util); + + expect(first).toHaveBeenCalledWith(matcherResult, matcherName, args, util); + expect(second).not.toHaveBeenCalled(); + expect(result).toEqual('first'); + }); + }); + }); + + describe('#modifyFailureMessage', function() { + describe('When no filters have #modifyFailureMessage', function() { + it('returns the original message', function() { + var chain = new jasmineUnderTest.ExpectationFilterChain(); + chain.addFilter({}); + expect(chain.modifyFailureMessage('msg')).toEqual('msg'); + }); + }); + + describe('When some filters have #modifyFailureMessage', function() { + it('calls the first filter that has #modifyFailureMessage', function() { + var first = jasmine.createSpy('first').and.returnValue('first'), + second = jasmine.createSpy('second').and.returnValue('second'), + chain = new jasmineUnderTest.ExpectationFilterChain() + .addFilter({modifyFailureMessage: first}) + .addFilter({modifyFailureMessage: second}), + result; + + result = chain.modifyFailureMessage('original'); + + expect(first).toHaveBeenCalledWith('original'); + expect(second).not.toHaveBeenCalled(); + expect(result).toEqual('first'); + }); + }); + }); +}); diff --git a/spec/core/ExpectationSpec.js b/spec/core/ExpectationSpec.js index be4a9986..72a4426f 100644 --- a/spec/core/ExpectationSpec.js +++ b/spec/core/ExpectationSpec.js @@ -6,7 +6,7 @@ describe("Expectation", function() { }, expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers }); @@ -22,31 +22,25 @@ describe("Expectation", function() { jasmineUnderTest.Expectation.addCoreMatchers(coreMatchers); - expectation = new jasmineUnderTest.Expectation({}); + expectation = jasmineUnderTest.Expectation.factory({}); expect(expectation.toQuux).toBeDefined(); }); - it("Factory builds an expectation/negative expectation", function() { - var builtExpectation = jasmineUnderTest.Expectation.Factory(); - - expect(builtExpectation instanceof jasmineUnderTest.Expectation).toBe(true); - expect(builtExpectation.not instanceof jasmineUnderTest.Expectation).toBe(true); - expect(builtExpectation.not.isNot).toBe(true); - }); - it("wraps matchers's compare functions, passing in matcher dependencies", function() { var fakeCompare = function() { return { pass: true }; }, matcherFactory = jasmine.createSpy("matcher").and.returnValue({ compare: fakeCompare }), matchers = { toFoo: matcherFactory }, - util = {}, + util = { + buildFailureMessage: jasmine.createSpy('buildFailureMessage') + }, customEqualityTesters = ['a'], addExpectationResult = jasmine.createSpy("addExpectationResult"), expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ util: util, customMatchers: matchers, customEqualityTesters: customEqualityTesters, @@ -74,7 +68,7 @@ describe("Expectation", function() { addExpectationResult = jasmine.createSpy("addExpectationResult"), expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ util: util, customMatchers: matchers, actual: "an actual", @@ -100,7 +94,7 @@ describe("Expectation", function() { addExpectationResult = jasmine.createSpy("addExpectationResult"), expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, util: util, actual: "an actual", @@ -115,7 +109,8 @@ describe("Expectation", function() { message: "", error: undefined, expected: "hello", - actual: "an actual" + actual: "an actual", + errorForStack: undefined }); }); @@ -133,7 +128,7 @@ describe("Expectation", function() { addExpectationResult = jasmine.createSpy("addExpectationResult"), expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, util: util, actual: "an actual", @@ -148,7 +143,8 @@ describe("Expectation", function() { expected: "hello", actual: "an actual", message: "", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -168,7 +164,7 @@ describe("Expectation", function() { addExpectationResult = jasmine.createSpy("addExpectationResult"), expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ actual: "an actual", customMatchers: matchers, addExpectationResult: addExpectationResult @@ -182,7 +178,8 @@ describe("Expectation", function() { expected: "hello", actual: "an actual", message: "I am a custom message", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -202,7 +199,7 @@ describe("Expectation", function() { addExpectationResult = jasmine.createSpy("addExpectationResult"), expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", addExpectationResult: addExpectationResult @@ -216,7 +213,8 @@ describe("Expectation", function() { expected: "hello", actual: "an actual", message: "I am a custom message", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -235,12 +233,11 @@ describe("Expectation", function() { actual = "an actual", expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", - addExpectationResult: addExpectationResult, - isNot: true - }); + addExpectationResult: addExpectationResult + }).not; expectation.toFoo("hello"); @@ -250,7 +247,8 @@ describe("Expectation", function() { message: "", error: undefined, expected: "hello", - actual: actual + actual: actual, + errorForStack: undefined }); }); @@ -269,13 +267,12 @@ describe("Expectation", function() { actual = "an actual", expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", util: util, addExpectationResult: addExpectationResult, - isNot: true - }); + }).not; expectation.toFoo("hello"); @@ -285,7 +282,8 @@ describe("Expectation", function() { expected: "hello", actual: actual, message: "default message", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -306,12 +304,11 @@ describe("Expectation", function() { actual = "an actual", expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", - addExpectationResult: addExpectationResult, - isNot: true - }); + addExpectationResult: addExpectationResult + }).not; expectation.toFoo("hello"); @@ -321,7 +318,8 @@ describe("Expectation", function() { expected: "hello", actual: actual, message: "I am a custom message", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -338,12 +336,11 @@ describe("Expectation", function() { actual = "an actual", expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", - addExpectationResult: addExpectationResult, - isNot: true - }); + addExpectationResult: addExpectationResult + }).not; expectation.toFoo("hello"); @@ -353,7 +350,8 @@ describe("Expectation", function() { expected: "hello", actual: actual, message: "", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -375,12 +373,11 @@ describe("Expectation", function() { actual = "an actual", expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", addExpectationResult: addExpectationResult, - isNot: true - }); + }).not; expectation.toFoo("hello"); @@ -390,10 +387,11 @@ describe("Expectation", function() { expected: "hello", actual: actual, message: "I'm a custom message", - error: undefined + error: undefined, + errorForStack: undefined }); }); - + it("reports a custom error message to the spec", function() { var customError = new Error("I am a custom error"); var matchers = { @@ -412,7 +410,7 @@ describe("Expectation", function() { addExpectationResult = jasmine.createSpy("addExpectationResult"), expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ actual: "an actual", customMatchers: matchers, addExpectationResult: addExpectationResult @@ -426,9 +424,222 @@ describe("Expectation", function() { expected: "hello", actual: "an actual", message: "I am a custom message", - error: customError + error: customError, + errorForStack: undefined }); }); + it("reports a custom message to the spec when a 'not' comparison fails", function() { + var customError = new Error("I am a custom error"); + var matchers = { + toFoo: function() { + return { + compare: function() { + return { + pass: true, + message: "I am a custom message", + error: customError + }; + } + }; + } + }, + addExpectationResult = jasmine.createSpy("addExpectationResult"), + expectation; + + expectation = jasmineUnderTest.Expectation.factory({ + actual: "an actual", + customMatchers: matchers, + addExpectationResult: addExpectationResult + }).not; + + expectation.toFoo("hello"); + + expect(addExpectationResult).toHaveBeenCalledWith(false, { + matcherName: "toFoo", + passed: false, + expected: "hello", + actual: "an actual", + message: "I am a custom message", + error: customError, + errorForStack: undefined + }); + }); + + it("reports a custom message func to the spec when a 'not' comparison fails", function() { + var customError = new Error("I am a custom error"); + var matchers = { + toFoo: function() { + return { + compare: function() { + return { + pass: true, + message: function() { return "I am a custom message"; }, + error: customError + }; + } + }; + } + }, + addExpectationResult = jasmine.createSpy("addExpectationResult"), + expectation; + + expectation = jasmineUnderTest.Expectation.factory({ + actual: "an actual", + customMatchers: matchers, + addExpectationResult: addExpectationResult + }).not; + + expectation.toFoo("hello"); + + expect(addExpectationResult).toHaveBeenCalledWith(false, { + matcherName: "toFoo", + passed: false, + expected: "hello", + actual: "an actual", + message: "I am a custom message", + error: customError, + errorForStack: undefined + }); + }); + + describe("#withContext", function() { + it("prepends the context to the generated failure message", function() { + var matchers = { + toFoo: function() { + return { + compare: function() { return { pass: false }; } + }; + } + }, + util = { + buildFailureMessage: function() { return "failure message"; } + }, + addExpectationResult = jasmine.createSpy("addExpectationResult"), + expectation = jasmineUnderTest.Expectation.factory({ + customMatchers: matchers, + util: util, + actual: "an actual", + addExpectationResult: addExpectationResult + }); + + expectation.withContext("Some context").toFoo("hello"); + + expect(addExpectationResult).toHaveBeenCalledWith(false, + jasmine.objectContaining({ + message: "Some context: failure message" + }) + ); + }); + + it("prepends the context to a custom failure message", function() { + var matchers = { + toFoo: function() { + return { + compare: function() { return { pass: false, message: "msg" }; } + }; + } + }, + addExpectationResult = jasmine.createSpy("addExpectationResult"), + expectation = jasmineUnderTest.Expectation.factory({ + customMatchers: matchers, + actual: "an actual", + addExpectationResult: addExpectationResult + }); + + expectation.withContext("Some context").toFoo("hello"); + + expect(addExpectationResult).toHaveBeenCalledWith(false, + jasmine.objectContaining({ + message: "Some context: msg" + }) + ); + }); + + it("prepends the context to a custom failure message from a function", function() { + var matchers = { + toFoo: function() { + return { + compare: function() { + return { + pass: false, + message: function() { return "msg"; } + }; + } + }; + } + }, + addExpectationResult = jasmine.createSpy("addExpectationResult"), + expectation = jasmineUnderTest.Expectation.factory({ + customMatchers: matchers, + actual: "an actual", + addExpectationResult: addExpectationResult + }); + + expectation.withContext("Some context").toFoo("hello"); + + expect(addExpectationResult).toHaveBeenCalledWith(false, + jasmine.objectContaining({ + message: "Some context: msg" + }) + ); + }); + + it("works with #not", function() { + var matchers = { + toFoo: function() { + return { + compare: function() { return { pass: true }; } + }; + } + }, + addExpectationResult = jasmine.createSpy("addExpectationResult"), + expectation = jasmineUnderTest.Expectation.factory({ + customMatchers: matchers, + util: jasmineUnderTest.matchersUtil, + actual: "an actual", + addExpectationResult: addExpectationResult + }); + + expectation.withContext("Some context").not.toFoo(); + + expect(addExpectationResult).toHaveBeenCalledWith(false, + jasmine.objectContaining({ + message: "Some context: Expected 'an actual' not to foo." + }) + ); + }); + + it("works with #not and a custom message", function() { + var customError = new Error("I am a custom error"); + var matchers = { + toFoo: function() { + return { + compare: function() { + return { + pass: true, + message: function() { return "I am a custom message"; }, + error: customError + }; + } + }; + } + }, + addExpectationResult = jasmine.createSpy("addExpectationResult"), + expectation = jasmineUnderTest.Expectation.factory({ + actual: "an actual", + customMatchers: matchers, + addExpectationResult: addExpectationResult + }); + + expectation.withContext("Some context").not.toFoo("hello"); + + expect(addExpectationResult).toHaveBeenCalledWith(false, + jasmine.objectContaining({ + message: "Some context: I am a custom message", + }) + ); + }); + }); }); diff --git a/spec/core/matchers/async/toBeRejectedSpec.js b/spec/core/matchers/async/toBeRejectedSpec.js new file mode 100644 index 00000000..ff718e49 --- /dev/null +++ b/spec/core/matchers/async/toBeRejectedSpec.js @@ -0,0 +1,23 @@ +describe('toBeRejected', function() { + it('passes if the actual is rejected', function() { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeRejected(jasmineUnderTest.matchersUtil), + actual = Promise.reject('AsyncExpectationSpec rejection'); + + return matcher.compare(actual).then(function(result) { + expect(result).toEqual(jasmine.objectContaining({pass: true})); + }); + }); + + it('fails if the actual is resolved', function() { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeRejected(jasmineUnderTest.matchersUtil), + actual = Promise.resolve(); + + return matcher.compare(actual).then(function(result) { + expect(result).toEqual(jasmine.objectContaining({pass: false})); + }); + }); +}); diff --git a/spec/core/matchers/async/toBeRejectedWithSpec.js b/spec/core/matchers/async/toBeRejectedWithSpec.js new file mode 100644 index 00000000..899d8a79 --- /dev/null +++ b/spec/core/matchers/async/toBeRejectedWithSpec.js @@ -0,0 +1,63 @@ +describe('#toBeRejectedWith', function () { + it('should return true if the promise is rejected with the expected value', function () { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(jasmineUnderTest.matchersUtil), + actual = Promise.reject({error: 'PEBCAK'}); + + return matcher.compare(actual, {error: 'PEBCAK'}).then(function (result) { + expect(result).toEqual(jasmine.objectContaining({ pass: true })); + }); + }); + + it('should fail if the promise resolves', function () { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(jasmineUnderTest.matchersUtil), + actual = Promise.resolve(); + + return matcher.compare(actual, '').then(function (result) { + expect(result).toEqual(jasmine.objectContaining({ pass: false })); + }); + }); + + it('should fail if the promise is rejected with a different value', function () { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(jasmineUnderTest.matchersUtil), + actual = Promise.reject('A Bad Apple'); + + return matcher.compare(actual, 'Some Cool Thing').then(function (result) { + expect(result).toEqual(jasmine.objectContaining({ + pass: false, + message: "Expected a promise to be rejected with 'Some Cool Thing' but it was rejected with 'A Bad Apple'.", + })); + }); + }); + + it('should build its error correctly when negated', function () { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(jasmineUnderTest.matchersUtil), + actual = Promise.reject(true); + + return matcher.compare(actual, true).then(function (result) { + expect(result).toEqual(jasmine.objectContaining({ + pass: true, + message: 'Expected a promise not to be rejected with true.' + })); + }); + }); + + it('should support custom equality testers', function () { + jasmine.getEnv().requirePromises(); + + var customEqualityTesters = [function() { return true; }], + matcher = jasmineUnderTest.asyncMatchers.toBeRejectedWith(jasmineUnderTest.matchersUtil, customEqualityTesters), + actual = Promise.reject('actual'); + + return matcher.compare(actual, 'expected').then(function(result) { + expect(result).toEqual(jasmine.objectContaining({pass: true})); + }); + }); +}); diff --git a/spec/core/matchers/async/toBeResolvedSpec.js b/spec/core/matchers/async/toBeResolvedSpec.js new file mode 100644 index 00000000..ba66ab67 --- /dev/null +++ b/spec/core/matchers/async/toBeResolvedSpec.js @@ -0,0 +1,23 @@ +describe('toBeResolved', function() { + it('passes if the actual is resolved', function() { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeResolved(jasmineUnderTest.matchersUtil), + actual = Promise.resolve(); + + return matcher.compare(actual).then(function(result) { + expect(result).toEqual(jasmine.objectContaining({pass: true})); + }); + }); + + it('fails if the actual is rejected', function() { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeResolved(jasmineUnderTest.matchersUtil), + actual = Promise.reject('AsyncExpectationSpec rejection'); + + return matcher.compare(actual).then(function(result) { + expect(result).toEqual(jasmine.objectContaining({pass: false})); + }); + }); +}); diff --git a/spec/core/matchers/async/toBeResolvedToSpec.js b/spec/core/matchers/async/toBeResolvedToSpec.js new file mode 100644 index 00000000..e8baaf7d --- /dev/null +++ b/spec/core/matchers/async/toBeResolvedToSpec.js @@ -0,0 +1,66 @@ +describe('#toBeResolvedTo', function() { + it('passes if the promise is resolved to the expected value', function() { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(jasmineUnderTest.matchersUtil), + actual = Promise.resolve({foo: 42}); + + return matcher.compare(actual, {foo: 42}).then(function(result) { + expect(result).toEqual(jasmine.objectContaining({pass: true})); + }); + }); + + it('fails if the promise is rejected', function() { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(jasmineUnderTest.matchersUtil), + actual = Promise.reject('AsyncExpectationSpec error'); + + return matcher.compare(actual, '').then(function(result) { + expect(result).toEqual(jasmine.objectContaining({ + pass: false, + message: "Expected a promise to be resolved to '' but it was rejected.", + })); + }); + }); + + it('fails if the promise is resolved to a different value', function() { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(jasmineUnderTest.matchersUtil), + actual = Promise.resolve({foo: 17}); + + return matcher.compare(actual, {foo: 42}).then(function(result) { + expect(result).toEqual(jasmine.objectContaining({ + pass: false, + message: 'Expected a promise to be resolved to Object({ foo: 42 }) but it was resolved to Object({ foo: 17 }).', + })); + }); + }); + + it('builds its message correctly when negated', function() { + jasmine.getEnv().requirePromises(); + + var matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(jasmineUnderTest.matchersUtil), + actual = Promise.resolve(true); + + return matcher.compare(actual, true).then(function(result) { + expect(result).toEqual(jasmine.objectContaining({ + pass: true, + message: 'Expected a promise not to be resolved to true.' + })); + }); + }); + + it('supports custom equality testers', function() { + jasmine.getEnv().requirePromises(); + + var customEqualityTesters = [function() { return true; }], + matcher = jasmineUnderTest.asyncMatchers.toBeResolvedTo(jasmineUnderTest.matchersUtil, customEqualityTesters), + actual = Promise.resolve('actual'); + + return matcher.compare(actual, 'expected').then(function(result) { + expect(result).toEqual(jasmine.objectContaining({pass: true})); + }); + }); +}); diff --git a/src/core/AsyncExpectation.js b/src/core/AsyncExpectation.js deleted file mode 100644 index 31f5f430..00000000 --- a/src/core/AsyncExpectation.js +++ /dev/null @@ -1,196 +0,0 @@ -getJasmineRequireObj().AsyncExpectation = function(j$) { - var promiseForMessage = { - jasmineToString: function() { return 'a promise'; } - }; - - /** - * Asynchronous matchers. - * @namespace async-matchers - */ - function AsyncExpectation(options) { - var global = options.global || j$.getGlobal(); - this.util = options.util || { buildFailureMessage: function() {} }; - this.customEqualityTesters = options.customEqualityTesters || []; - this.addExpectationResult = options.addExpectationResult || function(){}; - this.actual = options.actual; - this.isNot = options.isNot; - - if (!global.Promise) { - throw new Error('expectAsync is unavailable because the environment does not support promises.'); - } - - if (!j$.isPromiseLike(this.actual)) { - throw new Error('Expected expectAsync to be called with a promise.'); - } - - ['toBeResolved', 'toBeRejected', 'toBeResolvedTo', 'toBeRejectedWith'].forEach(wrapCompare.bind(this)); - } - - function wrapCompare(name) { - var compare = this[name]; - this[name] = function() { - var self = this; - var args = Array.prototype.slice.call(arguments); - args.unshift(this.actual); - - // Capture the call stack here, before we go async, so that it will - // contain frames that are relevant to the user instead of just parts - // of Jasmine. - var errorForStack = j$.util.errorWithStack(); - - return compare.apply(self, args).then(function(result) { - var message; - - if (self.isNot) { - result.pass = !result.pass; - } - - args[0] = promiseForMessage; - message = j$.Expectation.finalizeMessage(self.util, name, self.isNot, args, result); - - self.addExpectationResult(result.pass, { - matcherName: name, - passed: result.pass, - message: message, - error: undefined, - errorForStack: errorForStack, - actual: self.actual - }); - }); - }; - } - - /** - * Expect a promise to be resolved. - * @function - * @async - * @name async-matchers#toBeResolved - * @example - * await expectAsync(aPromise).toBeResolved(); - * @example - * return expectAsync(aPromise).toBeResolved(); - */ - AsyncExpectation.prototype.toBeResolved = function(actual) { - return actual.then( - function() { return {pass: true}; }, - function() { return {pass: false}; } - ); - }; - - /** - * Expect a promise to be rejected. - * @function - * @async - * @name async-matchers#toBeRejected - * @example - * await expectAsync(aPromise).toBeRejected(); - * @example - * return expectAsync(aPromise).toBeRejected(); - */ - AsyncExpectation.prototype.toBeRejected = function(actual) { - return actual.then( - function() { return {pass: false}; }, - function() { return {pass: true}; } - ); - }; - - /** - * Expect a promise to be resolved to a value equal to the expected, using deep equality comparison. - * @function - * @async - * @name async-matchers#toBeResolvedTo - * @param {Object} expected - Value that the promise is expected to resolve to - * @example - * await expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); - * @example - * return expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); - */ - AsyncExpectation.prototype.toBeResolvedTo = function(actualPromise, expectedValue) { - var self = this; - - function prefix(passed) { - return 'Expected a promise ' + - (passed ? 'not ' : '') + - 'to be resolved to ' + j$.pp(expectedValue); - } - - return actualPromise.then( - function(actualValue) { - if (self.util.equals(actualValue, expectedValue, self.customEqualityTesters)) { - return { - pass: true, - message: prefix(true) + '.' - }; - } else { - return { - pass: false, - message: prefix(false) + ' but it was resolved to ' + j$.pp(actualValue) + '.' - }; - } - }, - function() { - return { - pass: false, - message: prefix(false) + ' but it was rejected.' - }; - } - ); - }; - - /** - * Expect a promise to be rejected to a value equal to the expected, using deep equality comparison. - * @function - * @async - * @name async-matchers#toBeRejectedWith - * @param {Object} expected - Value that the promise is expected to reject to - * @example - * await expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); - * @example - * return expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); - */ - AsyncExpectation.prototype.toBeRejectedWith = function(actualPromise, expectedValue) { - var self = this; - - function prefix(passed) { - return 'Expected a promise ' + - (passed ? 'not ' : '') + - 'to be rejected to ' + j$.pp(expectedValue); - } - - return actualPromise.then( - function() { - return { - pass: false, - message: prefix(false) + ' but it was resolved.' - }; - }, - function(actualValue) { - if (self.util.equals(actualValue, expectedValue, self.customEqualityTesters)) { - return { - pass: true, - message: prefix(true) + '.' - }; - } else { - return { - pass: false, - message: prefix(false) + ' but it was rejected to ' + j$.pp(actualValue) + '.' - }; - } - } - ); - }; - - - AsyncExpectation.factory = function(options) { - var expect = new AsyncExpectation(options); - - options = j$.util.clone(options); - options.isNot = true; - expect.not = new AsyncExpectation(options); - - return expect; - }; - - - return AsyncExpectation; -}; diff --git a/src/core/Env.js b/src/core/Env.js index 19105525..3b9c2b97 100644 --- a/src/core/Env.js +++ b/src/core/Env.js @@ -193,6 +193,7 @@ getJasmineRequireObj().Env = function(j$) { }; j$.Expectation.addCoreMatchers(j$.matchers); + j$.Expectation.addAsyncCoreMatchers(j$.asyncMatchers); var nextSpecId = 0; var getNextSpecId = function() { @@ -205,7 +206,7 @@ getJasmineRequireObj().Env = function(j$) { }; var expectationFactory = function(actual, spec) { - return j$.Expectation.Factory({ + return j$.Expectation.factory({ util: j$.matchersUtil, customEqualityTesters: runnableResources[spec.id].customEqualityTesters, customMatchers: runnableResources[spec.id].customMatchers, @@ -219,7 +220,7 @@ getJasmineRequireObj().Env = function(j$) { }; var asyncExpectationFactory = function(actual, spec) { - return j$.AsyncExpectation.factory({ + return j$.Expectation.asyncFactory({ util: j$.matchersUtil, customEqualityTesters: runnableResources[spec.id].customEqualityTesters, actual: actual, diff --git a/src/core/Expectation.js b/src/core/Expectation.js index e302cc29..34f777a4 100644 --- a/src/core/Expectation.js +++ b/src/core/Expectation.js @@ -1,102 +1,154 @@ -getJasmineRequireObj().Expectation = function() { +getJasmineRequireObj().Expectation = function(j$) { + var promiseForMessage = { + jasmineToString: function() { return 'a promise'; } + }; /** * Matchers that come with Jasmine out of the box. * @namespace matchers */ function Expectation(options) { - this.util = options.util || { buildFailureMessage: function() {} }; - this.customEqualityTesters = options.customEqualityTesters || []; - this.actual = options.actual; - this.addExpectationResult = options.addExpectationResult || function(){}; - this.isNot = options.isNot; + this.expector = new j$.Expector(options); var customMatchers = options.customMatchers || {}; for (var matcherName in customMatchers) { - this[matcherName] = Expectation.prototype.wrapCompare(matcherName, customMatchers[matcherName]); + this[matcherName] = wrapSyncCompare(matcherName, customMatchers[matcherName]); } } - Expectation.prototype.wrapCompare = function(name, matcherFactory) { - return function() { - var args = Array.prototype.slice.call(arguments, 0), - expected = args.slice(0), - message; - - args.unshift(this.actual); - - var matcher = matcherFactory(this.util, this.customEqualityTesters), - matcherCompare = matcher.compare; - - function defaultNegativeCompare() { - var result = matcher.compare.apply(null, args); - result.pass = !result.pass; - return result; - } - - if (this.isNot) { - matcherCompare = matcher.negativeCompare || defaultNegativeCompare; - } - - var result = matcherCompare.apply(null, args); - message = Expectation.finalizeMessage(this.util, name, this.isNot, args, result); - - if (expected.length == 1) { - expected = expected[0]; - } - - // TODO: how many of these params are needed? - this.addExpectationResult( - result.pass, - { - matcherName: name, - passed: result.pass, - message: message, - error: result.error, - actual: this.actual, - expected: expected // TODO: this may need to be arrayified/sliced - } - ); - }; + Expectation.prototype.withContext = function withContext(message) { + return addFilter(this, new ContextAddingFilter(message)); }; - Expectation.finalizeMessage = function(util, name, isNot, args, result) { - if (result.pass) { - return ''; - } else if (result.message) { - if (Object.prototype.toString.apply(result.message) === '[object Function]') { + Object.defineProperty(Expectation.prototype, 'not', { + get: function() { + return addFilter(this, syncNegatingFilter); + } + }); + + /** + * Asynchronous matchers. + * @namespace async-matchers + */ + function AsyncExpectation(options) { + var global = options.global || j$.getGlobal(); + this.expector = new j$.Expector(options); + + if (!global.Promise) { + throw new Error('expectAsync is unavailable because the environment does not support promises.'); + } + + if (!j$.isPromiseLike(this.expector.actual)) { + throw new Error('Expected expectAsync to be called with a promise.'); + } + } + + AsyncExpectation.prototype.withContext = function withContext(message) { + return addFilter(this, new ContextAddingFilter(message)); + }; + + Object.defineProperty(AsyncExpectation.prototype, 'not', { + get: function() { + return addFilter(this, asyncNegatingFilter); + } + }); + + function wrapSyncCompare(name, matcherFactory) { + return function() { + var result = this.expector.compare(name, matcherFactory, arguments); + this.expector.processResult(result); + }; + } + + function wrapAsyncCompare(name, matcherFactory) { + return function() { + var self = this; + + // Capture the call stack here, before we go async, so that it will contain + // frames that are relevant to the user instead of just parts of Jasmine. + var errorForStack = j$.util.errorWithStack(); + + return this.expector.compare(name, matcherFactory, arguments).then(function(result) { + self.expector.processResult(result, errorForStack, promiseForMessage); + }); + }; + } + + function addCoreMatchers(prototype, matchers, wrapper) { + for (var matcherName in matchers) { + var matcher = matchers[matcherName]; + prototype[matcherName] = wrapper(matcherName, matcher); + } + } + + function addFilter(source, filter) { + var result = Object.create(source); + result.expector = source.expector.addFilter(filter); + return result; + } + + function negatedFailureMessage(result, matcherName, args, util) { + if (result.message) { + if (j$.isFunction_(result.message)) { return result.message(); } else { return result.message; } - } else { - args = args.slice(); - args.unshift(isNot); - args.unshift(name); - return util.buildFailureMessage.apply(null, args); + } + + args = args.slice(); + args.unshift(true); + args.unshift(matcherName); + return util.buildFailureMessage.apply(null, args); + } + + function negate(result) { + result.pass = !result.pass; + return result; + } + + var syncNegatingFilter = { + selectComparisonFunc: function(matcher) { + function defaultNegativeCompare() { + return negate(matcher.compare.apply(null, arguments)); + } + + return matcher.negativeCompare || defaultNegativeCompare; + }, + buildFailureMessage: negatedFailureMessage + }; + + var asyncNegatingFilter = { + selectComparisonFunc: function(matcher) { + function defaultNegativeCompare() { + return matcher.compare.apply(this, arguments).then(negate); + } + + return defaultNegativeCompare; + }, + buildFailureMessage: negatedFailureMessage + }; + + function ContextAddingFilter(message) { + this.message = message; + } + + ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { + return this.message + ': ' + msg; + }; + + return { + factory: function(options) { + return new Expectation(options || {}); + }, + addCoreMatchers: function(matchers) { + addCoreMatchers(Expectation.prototype, matchers, wrapSyncCompare); + }, + asyncFactory: function(options) { + return new AsyncExpectation(options || {}); + }, + addAsyncCoreMatchers: function(matchers) { + addCoreMatchers(AsyncExpectation.prototype, matchers, wrapAsyncCompare); } }; - - Expectation.addCoreMatchers = function(matchers) { - var prototype = Expectation.prototype; - for (var matcherName in matchers) { - var matcher = matchers[matcherName]; - prototype[matcherName] = prototype.wrapCompare(matcherName, matcher); - } - }; - - Expectation.Factory = function(options) { - options = options || {}; - - var expect = new Expectation(options); - - // TODO: this would be nice as its own Object - NegativeExpectation - // TODO: copy instead of mutate options - options.isNot = true; - expect.not = new Expectation(options); - - return expect; - }; - - return Expectation; }; diff --git a/src/core/ExpectationFilterChain.js b/src/core/ExpectationFilterChain.js new file mode 100644 index 00000000..83018bd6 --- /dev/null +++ b/src/core/ExpectationFilterChain.js @@ -0,0 +1,46 @@ +getJasmineRequireObj().ExpectationFilterChain = function() { + function ExpectationFilterChain(maybeFilter, prev) { + this.filter_ = maybeFilter; + this.prev_ = prev; + } + + ExpectationFilterChain.prototype.addFilter = function(filter) { + return new ExpectationFilterChain(filter, this); + }; + + ExpectationFilterChain.prototype.selectComparisonFunc = function(matcher) { + return this.callFirst_('selectComparisonFunc', arguments).result; + }; + + ExpectationFilterChain.prototype.buildFailureMessage = function(result, matcherName, args, util) { + return this.callFirst_('buildFailureMessage', arguments).result; + }; + + ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { + var result = this.callFirst_('modifyFailureMessage', arguments).result; + return result || msg; + }; + + ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { + var prevResult; + + if (this.prev_) { + prevResult = this.prev_.callFirst_(fname, args); + + if (prevResult.found) { + return prevResult; + } + } + + if (this.filter_ && this.filter_[fname]) { + return { + found: true, + result: this.filter_[fname].apply(this.filter_, args) + }; + } + + return {found: false}; + }; + + return ExpectationFilterChain; +}; diff --git a/src/core/Expector.js b/src/core/Expector.js new file mode 100644 index 00000000..a8c717f2 --- /dev/null +++ b/src/core/Expector.js @@ -0,0 +1,80 @@ +getJasmineRequireObj().Expector = function(j$) { + function Expector(options) { + this.util = options.util || { buildFailureMessage: function() {} }; + this.customEqualityTesters = options.customEqualityTesters || []; + this.actual = options.actual; + this.addExpectationResult = options.addExpectationResult || function(){}; + this.filters = new j$.ExpectationFilterChain(); + } + + Expector.prototype.instantiateMatcher = function(matcherName, matcherFactory, args) { + this.matcherName = matcherName; + this.args = Array.prototype.slice.call(args, 0); + this.expected = this.args.slice(0); + + this.args.unshift(this.actual); + + var matcher = matcherFactory(this.util, this.customEqualityTesters); + var comparisonFunc = this.filters.selectComparisonFunc(matcher); + return comparisonFunc || matcher.compare; + }; + + Expector.prototype.buildMessage = function(result) { + var self = this; + + if (result.pass) { + return ''; + } + + var msg = this.filters.buildFailureMessage(result, this.matcherName, this.args, this.util, defaultMessage); + return this.filters.modifyFailureMessage(msg || defaultMessage()); + + function defaultMessage() { + if (!result.message) { + var args = self.args.slice(); + args.unshift(false); + args.unshift(self.matcherName); + return self.util.buildFailureMessage.apply(null, args); + } else if (j$.isFunction_(result.message)) { + return result.message(); + } else { + return result.message; + } + } + }; + + Expector.prototype.compare = function(matcherName, matcherFactory, args) { + var matcherCompare = this.instantiateMatcher(matcherName, matcherFactory, args); + return matcherCompare.apply(null, this.args); + }; + + Expector.prototype.addFilter = function(filter) { + var result = Object.create(this); + result.filters = this.filters.addFilter(filter); + return result; + }; + + Expector.prototype.processResult = function(result, errorForStack, actualOverride) { + this.args[0] = actualOverride || this.args[0]; + var message = this.buildMessage(result); + + if (this.expected.length === 1) { + this.expected = this.expected[0]; + } + + this.addExpectationResult( + result.pass, + { + matcherName: this.matcherName, + passed: result.pass, + message: message, + error: errorForStack ? undefined : result.error, + errorForStack: errorForStack || undefined, + actual: this.actual, + expected: this.expected // TODO: this may need to be arrayified/sliced + } + ); + }; + + return Expector; +}; diff --git a/src/core/matchers/async/toBeRejected.js b/src/core/matchers/async/toBeRejected.js new file mode 100644 index 00000000..8451e8df --- /dev/null +++ b/src/core/matchers/async/toBeRejected.js @@ -0,0 +1,22 @@ +getJasmineRequireObj().toBeRejected = function(j$) { + /** + * Expect a promise to be rejected. + * @function + * @async + * @name async-matchers#toBeRejected + * @example + * await expectAsync(aPromise).toBeRejected(); + * @example + * return expectAsync(aPromise).toBeRejected(); + */ + return function toBeResolved(util) { + return { + compare: function(actual) { + return actual.then( + function() { return {pass: false}; }, + function() { return {pass: true}; } + ); + } + }; + }; +}; diff --git a/src/core/matchers/async/toBeRejectedWith.js b/src/core/matchers/async/toBeRejectedWith.js new file mode 100644 index 00000000..3e302de2 --- /dev/null +++ b/src/core/matchers/async/toBeRejectedWith.js @@ -0,0 +1,46 @@ +getJasmineRequireObj().toBeRejectedWith = function(j$) { + /** + * Expect a promise to be rejected with a value equal to the expected, using deep equality comparison. + * @function + * @async + * @name async-matchers#toBeRejectedWith + * @param {Object} expected - Value that the promise is expected to be rejected with + * @example + * await expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); + * @example + * return expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); + */ + return function toBeRejectedWith(util, customEqualityTesters) { + return { + compare: function(actualPromise, expectedValue) { + function prefix(passed) { + return 'Expected a promise ' + + (passed ? 'not ' : '') + + 'to be rejected with ' + j$.pp(expectedValue); + } + + return actualPromise.then( + function() { + return { + pass: false, + message: prefix(false) + ' but it was resolved.' + }; + }, + function(actualValue) { + if (util.equals(actualValue, expectedValue, customEqualityTesters)) { + return { + pass: true, + message: prefix(true) + '.' + }; + } else { + return { + pass: false, + message: prefix(false) + ' but it was rejected with ' + j$.pp(actualValue) + '.' + }; + } + } + ); + } + }; + }; +}; diff --git a/src/core/matchers/async/toBeResolved.js b/src/core/matchers/async/toBeResolved.js new file mode 100644 index 00000000..a26f265d --- /dev/null +++ b/src/core/matchers/async/toBeResolved.js @@ -0,0 +1,22 @@ +getJasmineRequireObj().toBeResolved = function(j$) { + /** + * Expect a promise to be resolved. + * @function + * @async + * @name async-matchers#toBeResolved + * @example + * await expectAsync(aPromise).toBeResolved(); + * @example + * return expectAsync(aPromise).toBeResolved(); + */ + return function toBeResolved(util) { + return { + compare: function(actual) { + return actual.then( + function() { return {pass: true}; }, + function() { return {pass: false}; } + ); + } + }; + }; +}; diff --git a/src/core/matchers/async/toBeResolvedTo.js b/src/core/matchers/async/toBeResolvedTo.js new file mode 100644 index 00000000..f178b673 --- /dev/null +++ b/src/core/matchers/async/toBeResolvedTo.js @@ -0,0 +1,46 @@ +getJasmineRequireObj().toBeResolvedTo = function(j$) { + /** + * Expect a promise to be resolved to a value equal to the expected, using deep equality comparison. + * @function + * @async + * @name async-matchers#toBeResolvedTo + * @param {Object} expected - Value that the promise is expected to resolve to + * @example + * await expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); + * @example + * return expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); + */ + return function toBeResolvedTo(util, customEqualityTesters) { + return { + compare: function(actualPromise, expectedValue) { + function prefix(passed) { + return 'Expected a promise ' + + (passed ? 'not ' : '') + + 'to be resolved to ' + j$.pp(expectedValue); + } + + return actualPromise.then( + function(actualValue) { + if (util.equals(actualValue, expectedValue, customEqualityTesters)) { + return { + pass: true, + message: prefix(true) + '.' + }; + } else { + return { + pass: false, + message: prefix(false) + ' but it was resolved to ' + j$.pp(actualValue) + '.' + }; + } + }, + function() { + return { + pass: false, + message: prefix(false) + ' but it was rejected.' + }; + } + ); + } + }; + }; +}; diff --git a/src/core/matchers/requireAsyncMatchers.js b/src/core/matchers/requireAsyncMatchers.js new file mode 100644 index 00000000..1474c22d --- /dev/null +++ b/src/core/matchers/requireAsyncMatchers.js @@ -0,0 +1,16 @@ +getJasmineRequireObj().requireAsyncMatchers = function(jRequire, j$) { + var availableMatchers = [ + 'toBeResolved', + 'toBeRejected', + 'toBeResolvedTo', + 'toBeRejectedWith' + ], + matchers = {}; + + for (var i = 0; i < availableMatchers.length; i++) { + var name = availableMatchers[i]; + matchers[name] = jRequire[name](j$); + } + + return matchers; +}; diff --git a/src/core/requireCore.js b/src/core/requireCore.js index 64645f68..8ff7448b 100644 --- a/src/core/requireCore.js +++ b/src/core/requireCore.js @@ -37,8 +37,9 @@ var getJasmineRequireObj = (function (jasmineGlobal) { j$.Env = jRequire.Env(j$); j$.StackTrace = jRequire.StackTrace(j$); j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); - j$.Expectation = jRequire.Expectation(); - j$.AsyncExpectation = jRequire.AsyncExpectation(j$); + j$.ExpectationFilterChain = jRequire.ExpectationFilterChain(); + j$.Expector = jRequire.Expector(j$); + j$.Expectation = jRequire.Expectation(j$); j$.buildExpectationResult = jRequire.buildExpectationResult(); j$.JsApiReporter = jRequire.JsApiReporter(); j$.matchersUtil = jRequire.matchersUtil(j$); @@ -71,6 +72,7 @@ var getJasmineRequireObj = (function (jasmineGlobal) { j$.NotEmpty = jRequire.NotEmpty(j$); j$.matchers = jRequire.requireMatchers(jRequire, j$); + j$.asyncMatchers = jRequire.requireAsyncMatchers(jRequire, j$); return j$; };