From 9fe9569b24777fbc9d58b1d2484cf0f4257650f8 Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Sun, 13 May 2018 22:48:20 -0700 Subject: [PATCH 01/14] Additional tests for negated matcher failure messages --- spec/core/ExpectationSpec.js | 72 ++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/spec/core/ExpectationSpec.js b/spec/core/ExpectationSpec.js index be4a9986..81668381 100644 --- a/spec/core/ExpectationSpec.js +++ b/spec/core/ExpectationSpec.js @@ -430,5 +430,77 @@ describe("Expectation", function() { }); }); + 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 + }); + }); + + 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 + }); + }); + }); From 533bda5d2400755a1ef49bfd59712af1f620496e Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Sun, 13 May 2018 12:14:35 -0700 Subject: [PATCH 02/14] Split Expectation#wrapCompare into several smaller functions --- lib/jasmine-core/jasmine.js | 107 +++++++++++++++++++----------------- src/core/Expectation.js | 107 +++++++++++++++++++----------------- 2 files changed, 116 insertions(+), 98 deletions(-) diff --git a/lib/jasmine-core/jasmine.js b/lib/jasmine-core/jasmine.js index eec02f48..6f5dfb76 100644 --- a/lib/jasmine-core/jasmine.js +++ b/lib/jasmine-core/jasmine.js @@ -2591,71 +2591,80 @@ getJasmineRequireObj().Expectation = function() { var customMatchers = options.customMatchers || {}; for (var matcherName in customMatchers) { - this[matcherName] = Expectation.prototype.wrapCompare(matcherName, customMatchers[matcherName]); + this[matcherName] = wrapCompare(matcherName, customMatchers[matcherName]); } } - Expectation.prototype.wrapCompare = function(name, matcherFactory) { + function wrapCompare(name, matcherFactory) { return function() { var args = Array.prototype.slice.call(arguments, 0), - expected = args.slice(0), - message = ''; + expected = args.slice(0); 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 matcherCompare = this.instantiateMatcher(matcherFactory); var result = matcherCompare.apply(null, args); - - if (!result.pass) { - if (!result.message) { - args.unshift(this.isNot); - args.unshift(name); - message = this.util.buildFailureMessage.apply(null, args); - } else { - if (Object.prototype.toString.apply(result.message) === '[object Function]') { - message = result.message(); - } else { - message = result.message; - } - } - } - - 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 - } - ); + this.processResult(result, name, expected, args); }; + } + + Expectation.prototype.instantiateMatcher = function(matcherFactory) { + var matcher = matcherFactory(this.util, this.customEqualityTesters); + + function defaultNegativeCompare() { + var result = matcher.compare.apply(null, arguments); + result.pass = !result.pass; + return result; + } + + if (this.isNot) { + return matcher.negativeCompare || defaultNegativeCompare; + } else { + return matcher.compare; + } + }; + + Expectation.prototype.processResult = function(result, name, expected, args) { + var message = this.buildMessage(result, name, args); + + 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.buildMessage = function(result, name, args) { + if (result.pass) { + return ''; + } else if (!result.message) { + args = args.slice(); + args.unshift(this.isNot); + args.unshift(name); + return this.util.buildFailureMessage.apply(null, args); + } else if (Object.prototype.toString.apply(result.message) === '[object Function]') { + return result.message(); + } else { + return result.message; + } }; Expectation.addCoreMatchers = function(matchers) { var prototype = Expectation.prototype; for (var matcherName in matchers) { var matcher = matchers[matcherName]; - prototype[matcherName] = prototype.wrapCompare(matcherName, matcher); + prototype[matcherName] = wrapCompare(matcherName, matcher); } }; diff --git a/src/core/Expectation.js b/src/core/Expectation.js index 8ebba620..496764d0 100644 --- a/src/core/Expectation.js +++ b/src/core/Expectation.js @@ -13,71 +13,80 @@ getJasmineRequireObj().Expectation = function() { var customMatchers = options.customMatchers || {}; for (var matcherName in customMatchers) { - this[matcherName] = Expectation.prototype.wrapCompare(matcherName, customMatchers[matcherName]); + this[matcherName] = wrapCompare(matcherName, customMatchers[matcherName]); } } - Expectation.prototype.wrapCompare = function(name, matcherFactory) { + function wrapCompare(name, matcherFactory) { return function() { var args = Array.prototype.slice.call(arguments, 0), - expected = args.slice(0), - message = ''; + expected = args.slice(0); 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 matcherCompare = this.instantiateMatcher(matcherFactory); var result = matcherCompare.apply(null, args); - - if (!result.pass) { - if (!result.message) { - args.unshift(this.isNot); - args.unshift(name); - message = this.util.buildFailureMessage.apply(null, args); - } else { - if (Object.prototype.toString.apply(result.message) === '[object Function]') { - message = result.message(); - } else { - message = result.message; - } - } - } - - 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 - } - ); + this.processResult(result, name, expected, args); }; + } + + Expectation.prototype.instantiateMatcher = function(matcherFactory) { + var matcher = matcherFactory(this.util, this.customEqualityTesters); + + function defaultNegativeCompare() { + var result = matcher.compare.apply(null, arguments); + result.pass = !result.pass; + return result; + } + + if (this.isNot) { + return matcher.negativeCompare || defaultNegativeCompare; + } else { + return matcher.compare; + } + }; + + Expectation.prototype.processResult = function(result, name, expected, args) { + var message = this.buildMessage(result, name, args); + + 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.buildMessage = function(result, name, args) { + if (result.pass) { + return ''; + } else if (!result.message) { + args = args.slice(); + args.unshift(this.isNot); + args.unshift(name); + return this.util.buildFailureMessage.apply(null, args); + } else if (Object.prototype.toString.apply(result.message) === '[object Function]') { + return result.message(); + } else { + return result.message; + } }; Expectation.addCoreMatchers = function(matchers) { var prototype = Expectation.prototype; for (var matcherName in matchers) { var matcher = matchers[matcherName]; - prototype[matcherName] = prototype.wrapCompare(matcherName, matcher); + prototype[matcherName] = wrapCompare(matcherName, matcher); } }; From 5cc22740c97bc467f295b1e6c762b6ff0cea4ac3 Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Sun, 13 May 2018 12:26:56 -0700 Subject: [PATCH 03/14] Test the public-ish interface --- spec/core/ExpectationSpec.js | 39 ++++++++++++------------------------ 1 file changed, 13 insertions(+), 26 deletions(-) diff --git a/spec/core/ExpectationSpec.js b/spec/core/ExpectationSpec.js index 81668381..e8422a96 100644 --- a/spec/core/ExpectationSpec.js +++ b/spec/core/ExpectationSpec.js @@ -27,14 +27,6 @@ describe("Expectation", function() { 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 }), @@ -235,12 +227,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"); @@ -269,13 +260,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"); @@ -306,12 +296,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"); @@ -338,12 +327,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"); @@ -375,12 +363,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"); From 282c436463a03fe74886b5887d749bcc422bf873 Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Sun, 13 May 2018 23:01:55 -0700 Subject: [PATCH 04/14] Implemented matcher negation as a filter --- lib/jasmine-core/jasmine.js | 39 +++++++++++++++++------- spec/core/ExpectationSpec.js | 1 - src/core/Expectation.js | 57 +++++++++++++++++++++++------------- src/core/requireCore.js | 2 +- 4 files changed, 67 insertions(+), 32 deletions(-) diff --git a/lib/jasmine-core/jasmine.js b/lib/jasmine-core/jasmine.js index 6f5dfb76..0fe31b92 100644 --- a/lib/jasmine-core/jasmine.js +++ b/lib/jasmine-core/jasmine.js @@ -2611,17 +2611,11 @@ getJasmineRequireObj().Expectation = function() { Expectation.prototype.instantiateMatcher = function(matcherFactory) { var matcher = matcherFactory(this.util, this.customEqualityTesters); - function defaultNegativeCompare() { - var result = matcher.compare.apply(null, arguments); - result.pass = !result.pass; - return result; + if (this.filter && this.filter.selectComparisonFunc) { + return this.filter.selectComparisonFunc(matcher); } - if (this.isNot) { - return matcher.negativeCompare || defaultNegativeCompare; - } else { - return matcher.compare; - } + return matcher.compare; }; Expectation.prototype.processResult = function(result, name, expected, args) { @@ -2648,9 +2642,11 @@ getJasmineRequireObj().Expectation = function() { Expectation.prototype.buildMessage = function(result, name, args) { if (result.pass) { return ''; + } else if (this.filter && this.filter.buildFailureMessage) { + return this.filter.buildFailureMessage(result, name, args, this.util); } else if (!result.message) { args = args.slice(); - args.unshift(this.isNot); + args.unshift(false); args.unshift(name); return this.util.buildFailureMessage.apply(null, args); } else if (Object.prototype.toString.apply(result.message) === '[object Function]') { @@ -2677,10 +2673,33 @@ getJasmineRequireObj().Expectation = function() { // TODO: copy instead of mutate options options.isNot = true; expect.not = new Expectation(options); + expect.not.filter = negatingFilter; return expect; }; + var negatingFilter = { + selectComparisonFunc: function(matcher) { + function defaultNegativeCompare() { + var result = matcher.compare.apply(null, arguments); + result.pass = !result.pass; + return result; + } + + return matcher.negativeCompare || defaultNegativeCompare; + }, + buildFailureMessage: function(result, matcherName, args, util) { + if (result.message) { + return result.message; + } + + args = args.slice(); + args.unshift(true); + args.unshift(matcherName); + return util.buildFailureMessage.apply(null, args); + } + }; + return Expectation; }; diff --git a/spec/core/ExpectationSpec.js b/spec/core/ExpectationSpec.js index e8422a96..0b87c875 100644 --- a/spec/core/ExpectationSpec.js +++ b/spec/core/ExpectationSpec.js @@ -488,6 +488,5 @@ describe("Expectation", function() { error: customError }); }); - }); diff --git a/src/core/Expectation.js b/src/core/Expectation.js index 496764d0..7527c1ee 100644 --- a/src/core/Expectation.js +++ b/src/core/Expectation.js @@ -1,4 +1,4 @@ -getJasmineRequireObj().Expectation = function() { +getJasmineRequireObj().Expectation = function(j$) { /** * Matchers that come with Jasmine out of the box. @@ -33,17 +33,11 @@ getJasmineRequireObj().Expectation = function() { Expectation.prototype.instantiateMatcher = function(matcherFactory) { var matcher = matcherFactory(this.util, this.customEqualityTesters); - function defaultNegativeCompare() { - var result = matcher.compare.apply(null, arguments); - result.pass = !result.pass; - return result; + if (this.filter && this.filter.selectComparisonFunc) { + return this.filter.selectComparisonFunc(matcher); } - if (this.isNot) { - return matcher.negativeCompare || defaultNegativeCompare; - } else { - return matcher.compare; - } + return matcher.compare; }; Expectation.prototype.processResult = function(result, name, expected, args) { @@ -70,12 +64,14 @@ getJasmineRequireObj().Expectation = function() { Expectation.prototype.buildMessage = function(result, name, args) { if (result.pass) { return ''; + } else if (this.filter && this.filter.buildFailureMessage) { + return this.filter.buildFailureMessage(result, name, args, this.util); } else if (!result.message) { args = args.slice(); - args.unshift(this.isNot); + args.unshift(false); args.unshift(name); return this.util.buildFailureMessage.apply(null, args); - } else if (Object.prototype.toString.apply(result.message) === '[object Function]') { + } else if (j$.isFunction_(result.message)) { return result.message(); } else { return result.message; @@ -91,17 +87,38 @@ getJasmineRequireObj().Expectation = function() { }; 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); + var expect = new Expectation(options || {}); + expect.not = Object.create(expect); + expect.not.filter = negatingFilter; return expect; }; + var negatingFilter = { + selectComparisonFunc: function(matcher) { + function defaultNegativeCompare() { + var result = matcher.compare.apply(null, arguments); + result.pass = !result.pass; + return result; + } + + return matcher.negativeCompare || defaultNegativeCompare; + }, + buildFailureMessage: function(result, matcherName, args, util) { + if (result.message) { + if (j$.isFunction_(result.message)) { + return result.message(); + } else { + return result.message; + } + } + + args = args.slice(); + args.unshift(true); + args.unshift(matcherName); + return util.buildFailureMessage.apply(null, args); + } + }; + return Expectation; }; diff --git a/src/core/requireCore.js b/src/core/requireCore.js index 95636ea8..abc12e67 100644 --- a/src/core/requireCore.js +++ b/src/core/requireCore.js @@ -37,7 +37,7 @@ var getJasmineRequireObj = (function (jasmineGlobal) { j$.Env = jRequire.Env(j$); j$.StackTrace = jRequire.StackTrace(j$); j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); - j$.Expectation = jRequire.Expectation(); + j$.Expectation = jRequire.Expectation(j$); j$.buildExpectationResult = jRequire.buildExpectationResult(); j$.JsApiReporter = jRequire.JsApiReporter(); j$.matchersUtil = jRequire.matchersUtil(j$); From e2897ce619538537ce148552358fc5898b242376 Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Mon, 14 May 2018 21:18:55 -0700 Subject: [PATCH 05/14] Added expect().withContext() to provide additional information in failure messages --- spec/core/ExpectationSpec.js | 83 ++++++++++++++++++++++++++++++++++++ src/core/Expectation.js | 42 ++++++++++++++---- 2 files changed, 116 insertions(+), 9 deletions(-) diff --git a/spec/core/ExpectationSpec.js b/spec/core/ExpectationSpec.js index 0b87c875..66e60e7d 100644 --- a/spec/core/ExpectationSpec.js +++ b/spec/core/ExpectationSpec.js @@ -488,5 +488,88 @@ describe("Expectation", function() { error: customError }); }); + + 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" + }) + ); + }); + }); }); diff --git a/src/core/Expectation.js b/src/core/Expectation.js index 7527c1ee..c8d09a02 100644 --- a/src/core/Expectation.js +++ b/src/core/Expectation.js @@ -62,19 +62,27 @@ getJasmineRequireObj().Expectation = function(j$) { }; Expectation.prototype.buildMessage = function(result, name, args) { + var util = this.util; + if (result.pass) { return ''; } else if (this.filter && this.filter.buildFailureMessage) { - return this.filter.buildFailureMessage(result, name, args, this.util); - } else if (!result.message) { - args = args.slice(); - args.unshift(false); - args.unshift(name); - return this.util.buildFailureMessage.apply(null, args); - } else if (j$.isFunction_(result.message)) { - return result.message(); + return this.filter.buildFailureMessage(result, name, args, util, defaultMessage); } else { - return result.message; + return defaultMessage(); + } + + function defaultMessage() { + if (!result.message) { + args = args.slice(); + args.unshift(false); + args.unshift(name); + return util.buildFailureMessage.apply(null, args); + } else if (j$.isFunction_(result.message)) { + return result.message(); + } else { + return result.message; + } } }; @@ -91,9 +99,16 @@ getJasmineRequireObj().Expectation = function(j$) { expect.not = Object.create(expect); expect.not.filter = negatingFilter; + expect.withContext = function(message) { + var filteredExpect = Object.create(expect); + filteredExpect.filter = new ContextAddingFilter(message); + return filteredExpect; + }; + return expect; }; + var negatingFilter = { selectComparisonFunc: function(matcher) { function defaultNegativeCompare() { @@ -120,5 +135,14 @@ getJasmineRequireObj().Expectation = function(j$) { } }; + + function ContextAddingFilter(message) { + this.message = message; + } + + ContextAddingFilter.prototype.buildFailureMessage = function(result, matcherName, args, util, getDefaultMessage) { + return this.message + ': ' + getDefaultMessage(); + }; + return Expectation; }; From 202a677637503d6992c85b72abde15be8bcff158 Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Sat, 19 May 2018 10:39:05 -0700 Subject: [PATCH 06/14] ExpectationFilterChain WIP --- spec/core/ExpectationFilterChainSpec.js | 78 +++++++++++++++++++++++++ src/core/ExpectationFilterChain.js | 43 ++++++++++++++ src/core/requireCore.js | 1 + 3 files changed, 122 insertions(+) create mode 100644 spec/core/ExpectationFilterChainSpec.js create mode 100644 src/core/ExpectationFilterChain.js diff --git a/spec/core/ExpectationFilterChainSpec.js b/spec/core/ExpectationFilterChainSpec.js new file mode 100644 index 00000000..8c91dd5a --- /dev/null +++ b/spec/core/ExpectationFilterChainSpec.js @@ -0,0 +1,78 @@ +describe('ExpectationFilterChainSpec', function() { + 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 chain = new jasmineUnderTest.ExpectationFilterChain(), + first = jasmine.createSpy('first').and.returnValue('first'), + second = jasmine.createSpy('second').and.returnValue('second'), + matcher = {}, + result; + + chain.addFilter({selectComparisonFunc: first}); + chain.addFilter({selectComparisonFunc: second}); + 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 chain = new jasmineUnderTest.ExpectationFilterChain(), + first = jasmine.createSpy('first').and.returnValue('first'), + second = jasmine.createSpy('second').and.returnValue('second'), + matcherResult = {pass: false}, + matcherName = 'foo', + args = [], + util = {}, + result; + + chain.addFilter({buildFailureMessage: first}); + chain.addFilter({buildFailureMessage: second}); + 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() { + it('calls each filter with the return value of the next previously added filter', function() { + var chain = new jasmineUnderTest.ExpectationFilterChain(), + first = jasmine.createSpy('first').and.returnValue('first'), + third = jasmine.createSpy('third').and.returnValue('third'), + result; + + chain.addFilter({modifyFailureMessage: first}); + chain.addFilter({}) + chain.addFilter({modifyFailureMessage: third}); + result = chain.modifyFailureMessage('original'); + + expect(third).toHaveBeenCalledWith('original'); + expect(first).toHaveBeenCalledWith('third'); + expect(result).toEqual('first'); + }); + }); +}); diff --git a/src/core/ExpectationFilterChain.js b/src/core/ExpectationFilterChain.js new file mode 100644 index 00000000..3577ab4c --- /dev/null +++ b/src/core/ExpectationFilterChain.js @@ -0,0 +1,43 @@ +getJasmineRequireObj().ExpectationFilterChain = function() { + function ExpectationFilterChain() { + this.filters_ = []; + } + + ExpectationFilterChain.prototype.addFilter = function(filter) { + this.filters_.push(filter); + }; + + ExpectationFilterChain.prototype.selectComparisonFunc = function(matcher) { + return this.callFirst_('selectComparisonFunc', arguments); + }; + + ExpectationFilterChain.prototype.buildFailureMessage = function(result, matcherName, args, util) { + return this.callFirst_('buildFailureMessage', arguments); + }; + + ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { + var i; + + for (i = this.filters_.length - 1; i >= 0; i--) { + if (this.filters_[i].modifyFailureMessage) { + msg = this.filters_[i].modifyFailureMessage(msg); + } + } + + return msg; + }; + + ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { + var i, filter; + + for (i = 0; i < this.filters_.length; i++) { + filter = this.filters_[i]; + + if (filter[fname]) { + return filter[fname].apply(filter, args); + } + } + }; + + return ExpectationFilterChain; +}; diff --git a/src/core/requireCore.js b/src/core/requireCore.js index abc12e67..252ba2a9 100644 --- a/src/core/requireCore.js +++ b/src/core/requireCore.js @@ -37,6 +37,7 @@ var getJasmineRequireObj = (function (jasmineGlobal) { j$.Env = jRequire.Env(j$); j$.StackTrace = jRequire.StackTrace(j$); j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); + j$.ExpectationFilterChain = jRequire.ExpectationFilterChain(); j$.Expectation = jRequire.Expectation(j$); j$.buildExpectationResult = jRequire.buildExpectationResult(); j$.JsApiReporter = jRequire.JsApiReporter(); From 321f161ce5538bc924199284512b35deb934298c Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Sat, 2 Jun 2018 13:57:29 -0700 Subject: [PATCH 07/14] Made ExpectationFilterChain immutable --- spec/core/ExpectationFilterChainSpec.js | 63 ++++++++++++++++++------- src/core/ExpectationFilterChain.js | 40 ++++++++++------ 2 files changed, 71 insertions(+), 32 deletions(-) diff --git a/spec/core/ExpectationFilterChainSpec.js b/spec/core/ExpectationFilterChainSpec.js index 8c91dd5a..81b3cfc4 100644 --- a/spec/core/ExpectationFilterChainSpec.js +++ b/spec/core/ExpectationFilterChainSpec.js @@ -1,4 +1,32 @@ -describe('ExpectationFilterChainSpec', function() { +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(); + debugger; + 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() { @@ -10,14 +38,14 @@ describe('ExpectationFilterChainSpec', function() { describe('When some filters have #selectComparisonFunc', function() { it('calls the first filter that has #selectComparisonFunc', function() { - var chain = new jasmineUnderTest.ExpectationFilterChain(), - first = jasmine.createSpy('first').and.returnValue('first'), + 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; - chain.addFilter({selectComparisonFunc: first}); - chain.addFilter({selectComparisonFunc: second}); result = chain.selectComparisonFunc(matcher); expect(first).toHaveBeenCalledWith(matcher); @@ -38,17 +66,17 @@ describe('ExpectationFilterChainSpec', function() { describe('When some filters have #buildFailureMessage', function() { it('calls the first filter that has #buildFailureMessage', function() { - var chain = new jasmineUnderTest.ExpectationFilterChain(), - first = jasmine.createSpy('first').and.returnValue('first'), + 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; - chain.addFilter({buildFailureMessage: first}); - chain.addFilter({buildFailureMessage: second}); result = chain.buildFailureMessage(matcherResult, matcherName, args, util); expect(first).toHaveBeenCalledWith(matcherResult, matcherName, args, util); @@ -60,19 +88,20 @@ describe('ExpectationFilterChainSpec', function() { describe('#modifyFailureMessage', function() { it('calls each filter with the return value of the next previously added filter', function() { - var chain = new jasmineUnderTest.ExpectationFilterChain(), - first = jasmine.createSpy('first').and.returnValue('first'), + var first = jasmine.createSpy('first').and.returnValue('first'), third = jasmine.createSpy('third').and.returnValue('third'), + chain = new jasmineUnderTest.ExpectationFilterChain() + .addFilter({modifyFailureMessage: first}) + .addFilter({}) + .addFilter({modifyFailureMessage: third}), result; - chain.addFilter({modifyFailureMessage: first}); - chain.addFilter({}) - chain.addFilter({modifyFailureMessage: third}); + debugger; result = chain.modifyFailureMessage('original'); - expect(third).toHaveBeenCalledWith('original'); - expect(first).toHaveBeenCalledWith('third'); - expect(result).toEqual('first'); + expect(first).toHaveBeenCalledWith('original'); + expect(third).toHaveBeenCalledWith('first'); + expect(result).toEqual('third'); }); }); }); diff --git a/src/core/ExpectationFilterChain.js b/src/core/ExpectationFilterChain.js index 3577ab4c..99cab978 100644 --- a/src/core/ExpectationFilterChain.js +++ b/src/core/ExpectationFilterChain.js @@ -1,42 +1,52 @@ getJasmineRequireObj().ExpectationFilterChain = function() { - function ExpectationFilterChain() { - this.filters_ = []; + function ExpectationFilterChain(maybeFilter, prev) { + this.filter_ = maybeFilter; + this.prev_ = prev; } ExpectationFilterChain.prototype.addFilter = function(filter) { - this.filters_.push(filter); + return new ExpectationFilterChain(filter, this); }; ExpectationFilterChain.prototype.selectComparisonFunc = function(matcher) { - return this.callFirst_('selectComparisonFunc', arguments); + return this.callFirst_('selectComparisonFunc', arguments).result; }; ExpectationFilterChain.prototype.buildFailureMessage = function(result, matcherName, args, util) { - return this.callFirst_('buildFailureMessage', arguments); + return this.callFirst_('buildFailureMessage', arguments).result; }; ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { - var i; + if (this.prev_) { + msg = this.prev_.modifyFailureMessage(msg); + } - for (i = this.filters_.length - 1; i >= 0; i--) { - if (this.filters_[i].modifyFailureMessage) { - msg = this.filters_[i].modifyFailureMessage(msg); - } + if (this.filter_ && this.filter_.modifyFailureMessage) { + msg = this.filter_.modifyFailureMessage(msg); } return msg; }; ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { - var i, filter; + var prevResult; - for (i = 0; i < this.filters_.length; i++) { - filter = this.filters_[i]; + if (this.prev_) { + prevResult = this.prev_.callFirst_(fname, args); - if (filter[fname]) { - return filter[fname].apply(filter, 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; From 8a01e1f26cb8e7b1e7939515e3c07a0e1e8c8b88 Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Sat, 2 Jun 2018 22:06:53 -0700 Subject: [PATCH 08/14] .withContext() works with .not --- spec/core/ExpectationSpec.js | 56 ++++++++++++++++++++++++++++++++++++ src/core/Expectation.js | 39 +++++++++++++------------ 2 files changed, 76 insertions(+), 19 deletions(-) diff --git a/spec/core/ExpectationSpec.js b/spec/core/ExpectationSpec.js index 66e60e7d..78088013 100644 --- a/spec/core/ExpectationSpec.js +++ b/spec/core/ExpectationSpec.js @@ -570,6 +570,62 @@ describe("Expectation", function() { }) ); }); + + 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/src/core/Expectation.js b/src/core/Expectation.js index c8d09a02..d5690d67 100644 --- a/src/core/Expectation.js +++ b/src/core/Expectation.js @@ -9,7 +9,7 @@ getJasmineRequireObj().Expectation = function(j$) { this.customEqualityTesters = options.customEqualityTesters || []; this.actual = options.actual; this.addExpectationResult = options.addExpectationResult || function(){}; - this.isNot = options.isNot; + this.filters = new j$.ExpectationFilterChain(); var customMatchers = options.customMatchers || {}; for (var matcherName in customMatchers) { @@ -32,12 +32,8 @@ getJasmineRequireObj().Expectation = function(j$) { Expectation.prototype.instantiateMatcher = function(matcherFactory) { var matcher = matcherFactory(this.util, this.customEqualityTesters); - - if (this.filter && this.filter.selectComparisonFunc) { - return this.filter.selectComparisonFunc(matcher); - } - - return matcher.compare; + var comparisonFunc = this.filters.selectComparisonFunc(matcher); + return comparisonFunc || matcher.compare; }; Expectation.prototype.processResult = function(result, name, expected, args) { @@ -62,16 +58,16 @@ getJasmineRequireObj().Expectation = function(j$) { }; Expectation.prototype.buildMessage = function(result, name, args) { - var util = this.util; + var util = this.util, + msg; if (result.pass) { return ''; - } else if (this.filter && this.filter.buildFailureMessage) { - return this.filter.buildFailureMessage(result, name, args, util, defaultMessage); - } else { - return defaultMessage(); } + msg = this.filters.buildFailureMessage(result, name, args, util, defaultMessage); + return this.filters.modifyFailureMessage(msg || defaultMessage()); + function defaultMessage() { if (!result.message) { args = args.slice(); @@ -86,6 +82,12 @@ getJasmineRequireObj().Expectation = function(j$) { } }; + Expectation.prototype.addFilter = function(filter) { + var result = Object.create(this); + result.filters = this.filters.addFilter(filter); + return result; + }; + Expectation.addCoreMatchers = function(matchers) { var prototype = Expectation.prototype; for (var matcherName in matchers) { @@ -96,13 +98,12 @@ getJasmineRequireObj().Expectation = function(j$) { Expectation.Factory = function(options) { var expect = new Expectation(options || {}); - expect.not = Object.create(expect); - expect.not.filter = negatingFilter; + expect.not = expect.addFilter(negatingFilter); expect.withContext = function(message) { - var filteredExpect = Object.create(expect); - filteredExpect.filter = new ContextAddingFilter(message); - return filteredExpect; + var result = this.addFilter(new ContextAddingFilter(message)); + result.not = result.addFilter(negatingFilter); + return result; }; return expect; @@ -140,8 +141,8 @@ getJasmineRequireObj().Expectation = function(j$) { this.message = message; } - ContextAddingFilter.prototype.buildFailureMessage = function(result, matcherName, args, util, getDefaultMessage) { - return this.message + ': ' + getDefaultMessage(); + ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { + return this.message + ': ' + msg; }; return Expectation; From 0842a80c6828271d1df3cbf35c47ff924b926e92 Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Sat, 9 Jun 2018 12:26:34 -0700 Subject: [PATCH 09/14] Cleanup --- spec/core/ExpectationFilterChainSpec.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/spec/core/ExpectationFilterChainSpec.js b/spec/core/ExpectationFilterChainSpec.js index 81b3cfc4..532af0c5 100644 --- a/spec/core/ExpectationFilterChainSpec.js +++ b/spec/core/ExpectationFilterChainSpec.js @@ -10,7 +10,6 @@ describe('ExpectationFilterChain', function() { added.modifyFailureMessage(); expect(first).toHaveBeenCalled(); - debugger; added.selectComparisonFunc(); expect(second).toHaveBeenCalled(); }); @@ -19,7 +18,6 @@ describe('ExpectationFilterChain', function() { var orig = new jasmineUnderTest.ExpectationFilterChain({}), f = jasmine.createSpy('f'); - orig.addFilter({selectComparisonFunc: f}); orig.selectComparisonFunc(); @@ -96,7 +94,6 @@ describe('ExpectationFilterChain', function() { .addFilter({modifyFailureMessage: third}), result; - debugger; result = chain.modifyFailureMessage('original'); expect(first).toHaveBeenCalledWith('original'); From ac07c9ea975989c345b7fac218319f6447e7566d Mon Sep 17 00:00:00 2001 From: Steve Gravrock Date: Sat, 9 Jun 2018 12:34:30 -0700 Subject: [PATCH 10/14] Simplified ExpectationFilterChain#modifyFailureMessage --- spec/core/ExpectationFilterChainSpec.js | 21 +++++++++++++++------ src/core/ExpectationFilterChain.js | 11 ++--------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/spec/core/ExpectationFilterChainSpec.js b/spec/core/ExpectationFilterChainSpec.js index 532af0c5..195fbe27 100644 --- a/spec/core/ExpectationFilterChainSpec.js +++ b/spec/core/ExpectationFilterChainSpec.js @@ -85,20 +85,29 @@ describe('ExpectationFilterChain', function() { }); describe('#modifyFailureMessage', function() { - it('calls each filter with the return value of the next previously added filter', 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'), - third = jasmine.createSpy('third').and.returnValue('third'), + second = jasmine.createSpy('second').and.returnValue('second'), chain = new jasmineUnderTest.ExpectationFilterChain() .addFilter({modifyFailureMessage: first}) - .addFilter({}) - .addFilter({modifyFailureMessage: third}), + .addFilter({modifyFailureMessage: second}), result; result = chain.modifyFailureMessage('original'); expect(first).toHaveBeenCalledWith('original'); - expect(third).toHaveBeenCalledWith('first'); - expect(result).toEqual('third'); + expect(second).not.toHaveBeenCalled(); + expect(result).toEqual('first'); + }); }); }); }); diff --git a/src/core/ExpectationFilterChain.js b/src/core/ExpectationFilterChain.js index 99cab978..83018bd6 100644 --- a/src/core/ExpectationFilterChain.js +++ b/src/core/ExpectationFilterChain.js @@ -17,15 +17,8 @@ getJasmineRequireObj().ExpectationFilterChain = function() { }; ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { - if (this.prev_) { - msg = this.prev_.modifyFailureMessage(msg); - } - - if (this.filter_ && this.filter_.modifyFailureMessage) { - msg = this.filter_.modifyFailureMessage(msg); - } - - return msg; + var result = this.callFirst_('modifyFailureMessage', arguments).result; + return result || msg; }; ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { From a91db0dfc2e394255855207e65e8685d561c5a06 Mon Sep 17 00:00:00 2001 From: Gregg Van Hove Date: Mon, 22 Oct 2018 16:08:57 -0700 Subject: [PATCH 11/14] more rejected to -> rejected with --- lib/jasmine-core/jasmine.js | 2 +- src/core/AsyncExpectation.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/jasmine-core/jasmine.js b/lib/jasmine-core/jasmine.js index a3320b56..acbf610f 100644 --- a/lib/jasmine-core/jasmine.js +++ b/lib/jasmine-core/jasmine.js @@ -2287,7 +2287,7 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { }; /** - * Expect a promise to be rejected to a value equal to the expected, using deep equality comparison. + * Expect a promise to be rejected with a value equal to the expected, using deep equality comparison. * @function * @async * @name async-matchers#toBeRejectedWith diff --git a/src/core/AsyncExpectation.js b/src/core/AsyncExpectation.js index 4b9e7ef0..e2d7d47f 100644 --- a/src/core/AsyncExpectation.js +++ b/src/core/AsyncExpectation.js @@ -141,7 +141,7 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { }; /** - * Expect a promise to be rejected to a value equal to the expected, using deep equality comparison. + * Expect a promise to be rejected with a value equal to the expected, using deep equality comparison. * @function * @async * @name async-matchers#toBeRejectedWith From ba1e8f8008848d08111649bcf52d98d311b0c7f9 Mon Sep 17 00:00:00 2001 From: Gregg Van Hove Date: Mon, 22 Oct 2018 16:42:36 -0700 Subject: [PATCH 12/14] Implement `withContext` for async expectations too --- lib/jasmine-core/jasmine.js | 14 ++++ spec/core/AsyncExpectationSpec.js | 131 ++++++++++++++++++++++++++++++ src/core/AsyncExpectation.js | 14 ++++ 3 files changed, 159 insertions(+) diff --git a/lib/jasmine-core/jasmine.js b/lib/jasmine-core/jasmine.js index acbf610f..4832011e 100644 --- a/lib/jasmine-core/jasmine.js +++ b/lib/jasmine-core/jasmine.js @@ -2339,6 +2339,12 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { var expect = new AsyncExpectation(options); expect.not = expect.addFilter(negatingFilter); + expect.withContext = function(message) { + var result = this.addFilter(new ContextAddingFilter(message)); + result.not = result.addFilter(negatingFilter); + return result; + }; + return expect; }; @@ -2370,6 +2376,14 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { }; + function ContextAddingFilter(message) { + this.message = message; + } + + ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { + return this.message + ': ' + msg; + }; + return AsyncExpectation; }; diff --git a/spec/core/AsyncExpectationSpec.js b/spec/core/AsyncExpectationSpec.js index 7aefa191..69459534 100644 --- a/spec/core/AsyncExpectationSpec.js +++ b/spec/core/AsyncExpectationSpec.js @@ -390,6 +390,137 @@ describe('AsyncExpectation', function() { ); }); + describe('#withContext', function() { + it("prepends the context to the generated failure message", function() { + jasmine.getEnv().requirePromises(); + + spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') + .and.returnValue(Promise.resolve({pass: false})); + + var util = { + buildFailureMessage: function() { return 'failure message'; } + }, + addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = dummyPromise(), + expectation = jasmineUnderTest.AsyncExpectation.factory({ + actual: actual, + 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(); + + spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') + .and.returnValue(Promise.resolve({pass: false, message: 'msg'})); + + var util = { + buildFailureMessage: function() { return 'failure message'; } + }, + addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = dummyPromise(), + expectation = jasmineUnderTest.AsyncExpectation.factory({ + 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("prepends the context to a custom failure message from a function", function() { + jasmine.getEnv().requirePromises(); + + spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') + .and.returnValue(Promise.resolve({pass: false, message: function() { return 'msg'; } })); + + var util = { + buildFailureMessage: function() { return 'failure message'; } + }, + addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = dummyPromise(), + expectation = jasmineUnderTest.AsyncExpectation.factory({ + 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(); + + spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') + .and.returnValue(Promise.resolve({pass: true})); + + var addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = dummyPromise(), + expectation = jasmineUnderTest.AsyncExpectation.factory({ + 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(); + + spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') + .and.returnValue(Promise.resolve({pass: true, message: 'msg'})); + + var addExpectationResult = jasmine.createSpy('addExpectationResult'), + actual = dummyPromise(), + expectation = jasmineUnderTest.AsyncExpectation.factory({ + 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: msg' + })); + }); + }); + }); + function dummyPromise() { return new Promise(function(resolve, reject) { }); diff --git a/src/core/AsyncExpectation.js b/src/core/AsyncExpectation.js index e2d7d47f..50d9dc82 100644 --- a/src/core/AsyncExpectation.js +++ b/src/core/AsyncExpectation.js @@ -193,6 +193,12 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { var expect = new AsyncExpectation(options); expect.not = expect.addFilter(negatingFilter); + expect.withContext = function(message) { + var result = this.addFilter(new ContextAddingFilter(message)); + result.not = result.addFilter(negatingFilter); + return result; + }; + return expect; }; @@ -224,5 +230,13 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { }; + function ContextAddingFilter(message) { + this.message = message; + } + + ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { + return this.message + ': ' + msg; + }; + return AsyncExpectation; }; From 1e47dcf2cc9d5acb00423d7267be33b1c5098939 Mon Sep 17 00:00:00 2001 From: Gregg Van Hove Date: Tue, 23 Oct 2018 16:02:31 -0700 Subject: [PATCH 13/14] Pull async matchers out to their own functions - Makes AsyncExpectation closer to Expectation --- lib/jasmine-core/jasmine.js | 332 ++++++++++------- spec/core/AsyncExpectationSpec.js | 349 +----------------- spec/core/matchers/async/toBeRejectedSpec.js | 23 ++ .../matchers/async/toBeRejectedWithSpec.js | 63 ++++ spec/core/matchers/async/toBeResolvedSpec.js | 23 ++ .../core/matchers/async/toBeResolvedToSpec.js | 66 ++++ src/core/AsyncExpectation.js | 172 ++------- src/core/Env.js | 1 + src/core/Expectation.js | 1 - src/core/matchers/async/toBeRejected.js | 22 ++ src/core/matchers/async/toBeRejectedWith.js | 46 +++ src/core/matchers/async/toBeResolved.js | 22 ++ src/core/matchers/async/toBeResolvedTo.js | 46 +++ src/core/matchers/requireAsyncMatchers.js | 16 + src/core/requireCore.js | 1 + 15 files changed, 566 insertions(+), 617 deletions(-) create mode 100644 spec/core/matchers/async/toBeRejectedSpec.js create mode 100644 spec/core/matchers/async/toBeRejectedWithSpec.js create mode 100644 spec/core/matchers/async/toBeResolvedSpec.js create mode 100644 spec/core/matchers/async/toBeResolvedToSpec.js create mode 100644 src/core/matchers/async/toBeRejected.js create mode 100644 src/core/matchers/async/toBeRejectedWith.js create mode 100644 src/core/matchers/async/toBeResolved.js create mode 100644 src/core/matchers/async/toBeResolvedTo.js create mode 100644 src/core/matchers/requireAsyncMatchers.js diff --git a/lib/jasmine-core/jasmine.js b/lib/jasmine-core/jasmine.js index 4832011e..57372e93 100644 --- a/lib/jasmine-core/jasmine.js +++ b/lib/jasmine-core/jasmine.js @@ -94,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$; }; @@ -969,6 +970,7 @@ getJasmineRequireObj().Env = function(j$) { }; j$.Expectation.addCoreMatchers(j$.matchers); + j$.AsyncExpectation.addCoreMatchers(j$.asyncMatchers); var nextSpecId = 0; var getNextSpecId = function() { @@ -2168,15 +2170,14 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { 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 matcher = this[name]; - this[name] = function() { + function wrapCompare(name, matcherFactory) { + return function() { var self = this; - var args = Array.prototype.slice.call(arguments); + var args = Array.prototype.slice.call(arguments), + expected = args.slice(0); + args.unshift(this.actual); // Capture the call stack here, before we go async, so that it will @@ -2184,155 +2185,48 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { // of Jasmine. var errorForStack = j$.util.errorWithStack(); - var matcherCompare = this.instantiateMatcher(matcher); + var matcherCompare = this.instantiateMatcher(matcherFactory); return matcherCompare.apply(self, args).then(function(result) { - var message; - args[0] = promiseForMessage; - message = j$.Expectation.prototype.buildMessage.call(self, result, name, args); - - self.addExpectationResult(result.pass, { - matcherName: name, - passed: result.pass, - message: message, - error: undefined, - errorForStack: errorForStack, - actual: self.actual - }); + self.processResult(result, name, expected, args, errorForStack); }); }; } - AsyncExpectation.prototype.instantiateMatcher = function(matcher) { - var comparisonFunc = this.filters.selectComparisonFunc(matcher); - return comparisonFunc || matcher; - }; + AsyncExpectation.prototype.processResult = function(result, name, expected, args, errorForStack) { + var message = this.buildMessage(result, name, args); - /** - * 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); + if (expected.length === 1) { + expected = expected[0]; } - 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.' - }; + this.addExpectationResult( + result.pass, + { + matcherName: name, + passed: result.pass, + message: message, + error: undefined, + errorForStack: errorForStack, + actual: this.actual, + expected: expected // TODO: this may need to be arrayified/sliced } ); }; - /** - * 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 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; + AsyncExpectation.prototype.buildMessage = j$.Expectation.prototype.buildMessage; - function prefix(passed) { - return 'Expected a promise ' + - (passed ? 'not ' : '') + - 'to be rejected with ' + j$.pp(expectedValue); + AsyncExpectation.prototype.instantiateMatcher = j$.Expectation.prototype.instantiateMatcher; + + AsyncExpectation.prototype.addFilter = j$.Expectation.prototype.addFilter; + + AsyncExpectation.addCoreMatchers = function(matchers) { + var prototype = AsyncExpectation.prototype; + for (var matcherName in matchers) { + var matcher = matchers[matcherName]; + prototype[matcherName] = wrapCompare(matcherName, matcher); } - - 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 with ' + j$.pp(actualValue) + '.' - }; - } - } - ); - }; - - AsyncExpectation.prototype.addFilter = function(filter) { - var result = Object.create(this); - result.filters = this.filters.addFilter(filter); - return result; }; AsyncExpectation.factory = function(options) { @@ -2351,7 +2245,7 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { var negatingFilter = { selectComparisonFunc: function(matcher) { function defaultNegativeCompare() { - return matcher.apply(this, arguments).then(function(result) { + return matcher.compare.apply(this, arguments).then(function(result) { result.pass = !result.pass; return result; }); @@ -3069,7 +2963,6 @@ getJasmineRequireObj().Expectation = function(j$) { expected = expected[0]; } - // TODO: how many of these params are needed? this.addExpectationResult( result.pass, { @@ -3358,6 +3251,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(), @@ -3948,6 +3981,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 69459534..3c260f13 100644 --- a/spec/core/AsyncExpectationSpec.js +++ b/spec/core/AsyncExpectationSpec.js @@ -1,4 +1,8 @@ describe('AsyncExpectation', function() { + beforeEach(function() { + jasmineUnderTest.AsyncExpectation.addCoreMatchers(jasmineUnderTest.asyncMatchers); + }); + describe('Factory', function() { it('throws an Error if promises are not available', function() { var thenable = {then: function() {}}, @@ -16,315 +20,6 @@ describe('AsyncExpectation', function() { }); }); - 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 with 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 with '' but it was resolved.", - error: undefined, - errorForStack: jasmine.any(Error), - actual: actual - }); - }); - }); - - it('should fail if the promise is rejected with 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 with 'Some Cool Thing' but it was rejected with '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 with 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(); @@ -394,16 +89,12 @@ describe('AsyncExpectation', function() { it("prepends the context to the generated failure message", function() { jasmine.getEnv().requirePromises(); - spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') - .and.returnValue(Promise.resolve({pass: false})); - var util = { buildFailureMessage: function() { return 'failure message'; } }, addExpectationResult = jasmine.createSpy('addExpectationResult'), - actual = dummyPromise(), expectation = jasmineUnderTest.AsyncExpectation.factory({ - actual: actual, + actual: Promise.reject('rejected'), addExpectationResult: addExpectationResult, util: util }); @@ -421,41 +112,35 @@ describe('AsyncExpectation', function() { it("prepends the context to a custom failure message", function() { jasmine.getEnv().requirePromises(); - spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') - .and.returnValue(Promise.resolve({pass: false, message: 'msg'})); - var util = { buildFailureMessage: function() { return 'failure message'; } }, addExpectationResult = jasmine.createSpy('addExpectationResult'), - actual = dummyPromise(), expectation = jasmineUnderTest.AsyncExpectation.factory({ - actual: actual, + actual: Promise.reject('b'), addExpectationResult: addExpectationResult, util: util }); - return expectation.withContext('Some context').toBeResolved() + return expectation.withContext('Some context').toBeResolvedTo('a') .then( function() { expect(addExpectationResult).toHaveBeenCalledWith(false, jasmine.objectContaining({ - message: 'Some context: msg' + 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(); - spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') - .and.returnValue(Promise.resolve({pass: false, message: function() { return 'msg'; } })); - var util = { buildFailureMessage: function() { return 'failure message'; } }, addExpectationResult = jasmine.createSpy('addExpectationResult'), - actual = dummyPromise(), + actual = Promise.reject(), expectation = jasmineUnderTest.AsyncExpectation.factory({ actual: actual, addExpectationResult: addExpectationResult, @@ -475,11 +160,8 @@ describe('AsyncExpectation', function() { it("works with #not", function() { jasmine.getEnv().requirePromises(); - spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') - .and.returnValue(Promise.resolve({pass: true})); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - actual = dummyPromise(), + actual = Promise.resolve(), expectation = jasmineUnderTest.AsyncExpectation.factory({ actual: actual, addExpectationResult: addExpectationResult, @@ -499,23 +181,20 @@ describe('AsyncExpectation', function() { it("works with #not and a custom message", function() { jasmine.getEnv().requirePromises(); - spyOn(jasmineUnderTest.AsyncExpectation.prototype, 'toBeResolved') - .and.returnValue(Promise.resolve({pass: true, message: 'msg'})); - var addExpectationResult = jasmine.createSpy('addExpectationResult'), - actual = dummyPromise(), + actual = Promise.resolve('a'), expectation = jasmineUnderTest.AsyncExpectation.factory({ actual: actual, addExpectationResult: addExpectationResult, util: jasmineUnderTest.matchersUtil }); - return expectation.withContext('Some context').not.toBeResolved() + return expectation.withContext('Some context').not.toBeResolvedTo('a') .then( function() { expect(addExpectationResult).toHaveBeenCalledWith(false, jasmine.objectContaining({ - message: 'Some context: msg' + message: "Some context: Expected a promise not to be resolved to 'a'." })); }); }); 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 index 50d9dc82..c88f699b 100644 --- a/src/core/AsyncExpectation.js +++ b/src/core/AsyncExpectation.js @@ -22,15 +22,14 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { 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 matcher = this[name]; - this[name] = function() { + function wrapCompare(name, matcherFactory) { + return function() { var self = this; - var args = Array.prototype.slice.call(arguments); + var args = Array.prototype.slice.call(arguments), + expected = args.slice(0); + args.unshift(this.actual); // Capture the call stack here, before we go async, so that it will @@ -38,155 +37,48 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { // of Jasmine. var errorForStack = j$.util.errorWithStack(); - var matcherCompare = this.instantiateMatcher(matcher); + var matcherCompare = this.instantiateMatcher(matcherFactory); return matcherCompare.apply(self, args).then(function(result) { - var message; - args[0] = promiseForMessage; - message = j$.Expectation.prototype.buildMessage.call(self, result, name, args); - - self.addExpectationResult(result.pass, { - matcherName: name, - passed: result.pass, - message: message, - error: undefined, - errorForStack: errorForStack, - actual: self.actual - }); + self.processResult(result, name, expected, args, errorForStack); }); }; } - AsyncExpectation.prototype.instantiateMatcher = function(matcher) { - var comparisonFunc = this.filters.selectComparisonFunc(matcher); - return comparisonFunc || matcher; - }; + AsyncExpectation.prototype.processResult = function(result, name, expected, args, errorForStack) { + var message = this.buildMessage(result, name, args); - /** - * 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); + if (expected.length === 1) { + expected = expected[0]; } - 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.' - }; + this.addExpectationResult( + result.pass, + { + matcherName: name, + passed: result.pass, + message: message, + error: undefined, + errorForStack: errorForStack, + actual: this.actual, + expected: expected // TODO: this may need to be arrayified/sliced } ); }; - /** - * 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 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; + AsyncExpectation.prototype.buildMessage = j$.Expectation.prototype.buildMessage; - function prefix(passed) { - return 'Expected a promise ' + - (passed ? 'not ' : '') + - 'to be rejected with ' + j$.pp(expectedValue); + AsyncExpectation.prototype.instantiateMatcher = j$.Expectation.prototype.instantiateMatcher; + + AsyncExpectation.prototype.addFilter = j$.Expectation.prototype.addFilter; + + AsyncExpectation.addCoreMatchers = function(matchers) { + var prototype = AsyncExpectation.prototype; + for (var matcherName in matchers) { + var matcher = matchers[matcherName]; + prototype[matcherName] = wrapCompare(matcherName, matcher); } - - 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 with ' + j$.pp(actualValue) + '.' - }; - } - } - ); - }; - - AsyncExpectation.prototype.addFilter = function(filter) { - var result = Object.create(this); - result.filters = this.filters.addFilter(filter); - return result; }; AsyncExpectation.factory = function(options) { @@ -205,7 +97,7 @@ getJasmineRequireObj().AsyncExpectation = function(j$) { var negatingFilter = { selectComparisonFunc: function(matcher) { function defaultNegativeCompare() { - return matcher.apply(this, arguments).then(function(result) { + return matcher.compare.apply(this, arguments).then(function(result) { result.pass = !result.pass; return result; }); diff --git a/src/core/Env.js b/src/core/Env.js index 19105525..a5f6c4df 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$.AsyncExpectation.addCoreMatchers(j$.asyncMatchers); var nextSpecId = 0; var getNextSpecId = function() { diff --git a/src/core/Expectation.js b/src/core/Expectation.js index 5367ab24..e6b6fc70 100644 --- a/src/core/Expectation.js +++ b/src/core/Expectation.js @@ -43,7 +43,6 @@ getJasmineRequireObj().Expectation = function(j$) { expected = expected[0]; } - // TODO: how many of these params are needed? this.addExpectationResult( result.pass, { 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 6ccacf44..181c2c32 100644 --- a/src/core/requireCore.js +++ b/src/core/requireCore.js @@ -72,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$; }; From 2d303a6e46e5904c10d61cce007f92a8e18961d3 Mon Sep 17 00:00:00 2001 From: Gregg Van Hove Date: Wed, 24 Oct 2018 16:17:30 -0700 Subject: [PATCH 14/14] Merge common async/sync expectation stuff --- lib/jasmine-core/jasmine.js | 429 +++++++++++++----------------- spec/core/AsyncExpectationSpec.js | 29 +- spec/core/ExpectationSpec.js | 78 +++--- src/core/AsyncExpectation.js | 134 ---------- src/core/Env.js | 6 +- src/core/Expectation.js | 205 +++++++------- src/core/Expector.js | 80 ++++++ src/core/requireCore.js | 2 +- 8 files changed, 441 insertions(+), 522 deletions(-) delete mode 100644 src/core/AsyncExpectation.js create mode 100644 src/core/Expector.js diff --git a/lib/jasmine-core/jasmine.js b/lib/jasmine-core/jasmine.js index 57372e93..b6bd9040 100644 --- a/lib/jasmine-core/jasmine.js +++ b/lib/jasmine-core/jasmine.js @@ -60,8 +60,8 @@ var getJasmineRequireObj = (function (jasmineGlobal) { j$.StackTrace = jRequire.StackTrace(j$); j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); j$.ExpectationFilterChain = jRequire.ExpectationFilterChain(); + j$.Expector = jRequire.Expector(j$); j$.Expectation = jRequire.Expectation(j$); - j$.AsyncExpectation = jRequire.AsyncExpectation(j$); j$.buildExpectationResult = jRequire.buildExpectationResult(); j$.JsApiReporter = jRequire.JsApiReporter(); j$.matchersUtil = jRequire.matchersUtil(j$); @@ -970,7 +970,7 @@ getJasmineRequireObj().Env = function(j$) { }; j$.Expectation.addCoreMatchers(j$.matchers); - j$.AsyncExpectation.addCoreMatchers(j$.asyncMatchers); + j$.Expectation.addAsyncCoreMatchers(j$.asyncMatchers); var nextSpecId = 0; var getNextSpecId = function() { @@ -983,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, @@ -997,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, @@ -2146,141 +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.filters = new j$.ExpectationFilterChain(); - - 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.'); - } - } - - function wrapCompare(name, matcherFactory) { - return function() { - var self = this; - var args = Array.prototype.slice.call(arguments), - expected = args.slice(0); - - 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(); - - var matcherCompare = this.instantiateMatcher(matcherFactory); - - return matcherCompare.apply(self, args).then(function(result) { - args[0] = promiseForMessage; - self.processResult(result, name, expected, args, errorForStack); - }); - }; - } - - AsyncExpectation.prototype.processResult = function(result, name, expected, args, errorForStack) { - var message = this.buildMessage(result, name, args); - - if (expected.length === 1) { - expected = expected[0]; - } - - this.addExpectationResult( - result.pass, - { - matcherName: name, - passed: result.pass, - message: message, - error: undefined, - errorForStack: errorForStack, - actual: this.actual, - expected: expected // TODO: this may need to be arrayified/sliced - } - ); - }; - - AsyncExpectation.prototype.buildMessage = j$.Expectation.prototype.buildMessage; - - AsyncExpectation.prototype.instantiateMatcher = j$.Expectation.prototype.instantiateMatcher; - - AsyncExpectation.prototype.addFilter = j$.Expectation.prototype.addFilter; - - AsyncExpectation.addCoreMatchers = function(matchers) { - var prototype = AsyncExpectation.prototype; - for (var matcherName in matchers) { - var matcher = matchers[matcherName]; - prototype[matcherName] = wrapCompare(matcherName, matcher); - } - }; - - AsyncExpectation.factory = function(options) { - var expect = new AsyncExpectation(options); - expect.not = expect.addFilter(negatingFilter); - - expect.withContext = function(message) { - var result = this.addFilter(new ContextAddingFilter(message)); - result.not = result.addFilter(negatingFilter); - return result; - }; - - return expect; - }; - - var negatingFilter = { - selectComparisonFunc: function(matcher) { - function defaultNegativeCompare() { - return matcher.compare.apply(this, arguments).then(function(result) { - result.pass = !result.pass; - return result; - }); - } - - return defaultNegativeCompare; - }, - buildFailureMessage: function(result, matcherName, args, util) { - if (result.message) { - if (j$.isFunction_(result.message)) { - return result.message(); - } else { - return result.message; - } - } - - args = args.slice(); - args.unshift(true); - args.unshift(matcherName); - return util.buildFailureMessage.apply(null, args); - } - }; - - - function ContextAddingFilter(message) { - this.message = message; - } - - ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { - return this.message + ': ' + msg; - }; - - return AsyncExpectation; -}; - getJasmineRequireObj().CallTracker = function(j$) { /** @@ -2919,141 +2784,135 @@ getJasmineRequireObj().ExceptionFormatter = function(j$) { }; 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.filters = new j$.ExpectationFilterChain(); + this.expector = new j$.Expector(options); var customMatchers = options.customMatchers || {}; for (var matcherName in customMatchers) { - this[matcherName] = wrapCompare(matcherName, customMatchers[matcherName]); + this[matcherName] = wrapSyncCompare(matcherName, customMatchers[matcherName]); } } - function wrapCompare(name, matcherFactory) { + Expectation.prototype.withContext = function withContext(message) { + return addFilter(this, new ContextAddingFilter(message)); + }; + + 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 args = Array.prototype.slice.call(arguments, 0), - expected = args.slice(0); - - args.unshift(this.actual); - - var matcherCompare = this.instantiateMatcher(matcherFactory); - var result = matcherCompare.apply(null, args); - this.processResult(result, name, expected, args); + var result = this.expector.compare(name, matcherFactory, arguments); + this.expector.processResult(result); }; } - Expectation.prototype.instantiateMatcher = function(matcherFactory) { - var matcher = matcherFactory(this.util, this.customEqualityTesters); - var comparisonFunc = this.filters.selectComparisonFunc(matcher); - return comparisonFunc || matcher.compare; - }; + function wrapAsyncCompare(name, matcherFactory) { + return function() { + var self = this; - Expectation.prototype.processResult = function(result, name, expected, args) { - var message = this.buildMessage(result, name, args); + // 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(); - if (expected.length === 1) { - expected = expected[0]; + 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); } + } - 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 - } - ); - }; + function addFilter(source, filter) { + var result = Object.create(source); + result.expector = source.expector.addFilter(filter); + return result; + } - Expectation.prototype.buildMessage = function(result, name, args) { - var util = this.util; - - if (result.pass) { - return ''; - } - - var msg = this.filters.buildFailureMessage(result, name, args, util, defaultMessage); - return this.filters.modifyFailureMessage(msg || defaultMessage()); - - function defaultMessage() { - if (!result.message) { - args = args.slice(); - args.unshift(false); - args.unshift(name); - return util.buildFailureMessage.apply(null, args); - } else if (j$.isFunction_(result.message)) { + function negatedFailureMessage(result, matcherName, args, util) { + if (result.message) { + if (j$.isFunction_(result.message)) { return result.message(); } else { return result.message; } } - }; - Expectation.prototype.addFilter = function(filter) { - var result = Object.create(this); - result.filters = this.filters.addFilter(filter); + args = args.slice(); + args.unshift(true); + args.unshift(matcherName); + return util.buildFailureMessage.apply(null, args); + } + + function negate(result) { + result.pass = !result.pass; return result; - }; + } - Expectation.addCoreMatchers = function(matchers) { - var prototype = Expectation.prototype; - for (var matcherName in matchers) { - var matcher = matchers[matcherName]; - prototype[matcherName] = wrapCompare(matcherName, matcher); - } - }; - - Expectation.Factory = function(options) { - var expect = new Expectation(options || {}); - expect.not = expect.addFilter(negatingFilter); - - expect.withContext = function(message) { - var result = this.addFilter(new ContextAddingFilter(message)); - result.not = result.addFilter(negatingFilter); - return result; - }; - - return expect; - }; - - - var negatingFilter = { + var syncNegatingFilter = { selectComparisonFunc: function(matcher) { function defaultNegativeCompare() { - var result = matcher.compare.apply(null, arguments); - result.pass = !result.pass; - return result; + return negate(matcher.compare.apply(null, arguments)); } return matcher.negativeCompare || defaultNegativeCompare; }, - buildFailureMessage: function(result, matcherName, args, util) { - if (result.message) { - if (j$.isFunction_(result.message)) { - return result.message(); - } else { - return result.message; - } - } - - args = args.slice(); - args.unshift(true); - args.unshift(matcherName); - return util.buildFailureMessage.apply(null, args); - } + 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; @@ -3063,7 +2922,20 @@ getJasmineRequireObj().Expectation = function(j$) { return this.message + ': ' + msg; }; - return Expectation; + 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); + } + }; }; getJasmineRequireObj().ExpectationFilterChain = function() { @@ -3179,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 : ''; diff --git a/spec/core/AsyncExpectationSpec.js b/spec/core/AsyncExpectationSpec.js index 3c260f13..906b3081 100644 --- a/spec/core/AsyncExpectationSpec.js +++ b/spec/core/AsyncExpectationSpec.js @@ -1,20 +1,20 @@ describe('AsyncExpectation', function() { beforeEach(function() { - jasmineUnderTest.AsyncExpectation.addCoreMatchers(jasmineUnderTest.asyncMatchers); + 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.'); }); @@ -26,7 +26,7 @@ describe('AsyncExpectation', function() { var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.resolve(), - expectation = jasmineUnderTest.AsyncExpectation.factory({ + expectation = jasmineUnderTest.Expectation.asyncFactory({ util: jasmineUnderTest.matchersUtil, actual: actual, addExpectationResult: addExpectationResult @@ -47,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 @@ -66,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'); }, @@ -93,7 +94,7 @@ describe('AsyncExpectation', function() { buildFailureMessage: function() { return 'failure message'; } }, addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = jasmineUnderTest.AsyncExpectation.factory({ + expectation = jasmineUnderTest.Expectation.asyncFactory({ actual: Promise.reject('rejected'), addExpectationResult: addExpectationResult, util: util @@ -116,7 +117,7 @@ describe('AsyncExpectation', function() { buildFailureMessage: function() { return 'failure message'; } }, addExpectationResult = jasmine.createSpy('addExpectationResult'), - expectation = jasmineUnderTest.AsyncExpectation.factory({ + expectation = jasmineUnderTest.Expectation.asyncFactory({ actual: Promise.reject('b'), addExpectationResult: addExpectationResult, util: util @@ -141,7 +142,7 @@ describe('AsyncExpectation', function() { }, addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.reject(), - expectation = jasmineUnderTest.AsyncExpectation.factory({ + expectation = jasmineUnderTest.Expectation.asyncFactory({ actual: actual, addExpectationResult: addExpectationResult, util: util @@ -162,7 +163,7 @@ describe('AsyncExpectation', function() { var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.resolve(), - expectation = jasmineUnderTest.AsyncExpectation.factory({ + expectation = jasmineUnderTest.Expectation.asyncFactory({ actual: actual, addExpectationResult: addExpectationResult, util: jasmineUnderTest.matchersUtil @@ -183,7 +184,7 @@ describe('AsyncExpectation', function() { var addExpectationResult = jasmine.createSpy('addExpectationResult'), actual = Promise.resolve('a'), - expectation = jasmineUnderTest.AsyncExpectation.factory({ + expectation = jasmineUnderTest.Expectation.asyncFactory({ actual: actual, addExpectationResult: addExpectationResult, util: jasmineUnderTest.matchersUtil diff --git a/spec/core/ExpectationSpec.js b/spec/core/ExpectationSpec.js index e0471c08..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,7 +22,7 @@ describe("Expectation", function() { jasmineUnderTest.Expectation.addCoreMatchers(coreMatchers); - expectation = new jasmineUnderTest.Expectation({}); + expectation = jasmineUnderTest.Expectation.factory({}); expect(expectation.toQuux).toBeDefined(); }); @@ -40,7 +40,7 @@ describe("Expectation", function() { addExpectationResult = jasmine.createSpy("addExpectationResult"), expectation; - expectation = new jasmineUnderTest.Expectation({ + expectation = jasmineUnderTest.Expectation.factory({ util: util, customMatchers: matchers, customEqualityTesters: customEqualityTesters, @@ -68,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", @@ -94,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", @@ -109,7 +109,8 @@ describe("Expectation", function() { message: "", error: undefined, expected: "hello", - actual: "an actual" + actual: "an actual", + errorForStack: undefined }); }); @@ -127,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", @@ -142,7 +143,8 @@ describe("Expectation", function() { expected: "hello", actual: "an actual", message: "", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -162,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 @@ -176,7 +178,8 @@ describe("Expectation", function() { expected: "hello", actual: "an actual", message: "I am a custom message", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -196,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 @@ -210,7 +213,8 @@ describe("Expectation", function() { expected: "hello", actual: "an actual", message: "I am a custom message", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -229,7 +233,7 @@ describe("Expectation", function() { actual = "an actual", expectation; - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", addExpectationResult: addExpectationResult @@ -243,7 +247,8 @@ describe("Expectation", function() { message: "", error: undefined, expected: "hello", - actual: actual + actual: actual, + errorForStack: undefined }); }); @@ -262,7 +267,7 @@ describe("Expectation", function() { actual = "an actual", expectation; - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", util: util, @@ -277,7 +282,8 @@ describe("Expectation", function() { expected: "hello", actual: actual, message: "default message", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -298,7 +304,7 @@ describe("Expectation", function() { actual = "an actual", expectation; - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", addExpectationResult: addExpectationResult @@ -312,7 +318,8 @@ describe("Expectation", function() { expected: "hello", actual: actual, message: "I am a custom message", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -329,7 +336,7 @@ describe("Expectation", function() { actual = "an actual", expectation; - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", addExpectationResult: addExpectationResult @@ -343,7 +350,8 @@ describe("Expectation", function() { expected: "hello", actual: actual, message: "", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -365,7 +373,7 @@ describe("Expectation", function() { actual = "an actual", expectation; - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", addExpectationResult: addExpectationResult, @@ -379,7 +387,8 @@ describe("Expectation", function() { expected: "hello", actual: actual, message: "I'm a custom message", - error: undefined + error: undefined, + errorForStack: undefined }); }); @@ -401,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 @@ -415,7 +424,8 @@ describe("Expectation", function() { expected: "hello", actual: "an actual", message: "I am a custom message", - error: customError + error: customError, + errorForStack: undefined }); }); @@ -437,7 +447,7 @@ describe("Expectation", function() { addExpectationResult = jasmine.createSpy("addExpectationResult"), expectation; - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ actual: "an actual", customMatchers: matchers, addExpectationResult: addExpectationResult @@ -451,7 +461,8 @@ describe("Expectation", function() { expected: "hello", actual: "an actual", message: "I am a custom message", - error: customError + error: customError, + errorForStack: undefined }); }); @@ -473,7 +484,7 @@ describe("Expectation", function() { addExpectationResult = jasmine.createSpy("addExpectationResult"), expectation; - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ actual: "an actual", customMatchers: matchers, addExpectationResult: addExpectationResult @@ -487,7 +498,8 @@ describe("Expectation", function() { expected: "hello", actual: "an actual", message: "I am a custom message", - error: customError + error: customError, + errorForStack: undefined }); }); @@ -504,7 +516,7 @@ describe("Expectation", function() { buildFailureMessage: function() { return "failure message"; } }, addExpectationResult = jasmine.createSpy("addExpectationResult"), - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, util: util, actual: "an actual", @@ -529,7 +541,7 @@ describe("Expectation", function() { } }, addExpectationResult = jasmine.createSpy("addExpectationResult"), - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", addExpectationResult: addExpectationResult @@ -558,7 +570,7 @@ describe("Expectation", function() { } }, addExpectationResult = jasmine.createSpy("addExpectationResult"), - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, actual: "an actual", addExpectationResult: addExpectationResult @@ -582,7 +594,7 @@ describe("Expectation", function() { } }, addExpectationResult = jasmine.createSpy("addExpectationResult"), - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ customMatchers: matchers, util: jasmineUnderTest.matchersUtil, actual: "an actual", @@ -614,7 +626,7 @@ describe("Expectation", function() { } }, addExpectationResult = jasmine.createSpy("addExpectationResult"), - expectation = jasmineUnderTest.Expectation.Factory({ + expectation = jasmineUnderTest.Expectation.factory({ actual: "an actual", customMatchers: matchers, addExpectationResult: addExpectationResult diff --git a/src/core/AsyncExpectation.js b/src/core/AsyncExpectation.js deleted file mode 100644 index c88f699b..00000000 --- a/src/core/AsyncExpectation.js +++ /dev/null @@ -1,134 +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.filters = new j$.ExpectationFilterChain(); - - 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.'); - } - } - - function wrapCompare(name, matcherFactory) { - return function() { - var self = this; - var args = Array.prototype.slice.call(arguments), - expected = args.slice(0); - - 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(); - - var matcherCompare = this.instantiateMatcher(matcherFactory); - - return matcherCompare.apply(self, args).then(function(result) { - args[0] = promiseForMessage; - self.processResult(result, name, expected, args, errorForStack); - }); - }; - } - - AsyncExpectation.prototype.processResult = function(result, name, expected, args, errorForStack) { - var message = this.buildMessage(result, name, args); - - if (expected.length === 1) { - expected = expected[0]; - } - - this.addExpectationResult( - result.pass, - { - matcherName: name, - passed: result.pass, - message: message, - error: undefined, - errorForStack: errorForStack, - actual: this.actual, - expected: expected // TODO: this may need to be arrayified/sliced - } - ); - }; - - AsyncExpectation.prototype.buildMessage = j$.Expectation.prototype.buildMessage; - - AsyncExpectation.prototype.instantiateMatcher = j$.Expectation.prototype.instantiateMatcher; - - AsyncExpectation.prototype.addFilter = j$.Expectation.prototype.addFilter; - - AsyncExpectation.addCoreMatchers = function(matchers) { - var prototype = AsyncExpectation.prototype; - for (var matcherName in matchers) { - var matcher = matchers[matcherName]; - prototype[matcherName] = wrapCompare(matcherName, matcher); - } - }; - - AsyncExpectation.factory = function(options) { - var expect = new AsyncExpectation(options); - expect.not = expect.addFilter(negatingFilter); - - expect.withContext = function(message) { - var result = this.addFilter(new ContextAddingFilter(message)); - result.not = result.addFilter(negatingFilter); - return result; - }; - - return expect; - }; - - var negatingFilter = { - selectComparisonFunc: function(matcher) { - function defaultNegativeCompare() { - return matcher.compare.apply(this, arguments).then(function(result) { - result.pass = !result.pass; - return result; - }); - } - - return defaultNegativeCompare; - }, - buildFailureMessage: function(result, matcherName, args, util) { - if (result.message) { - if (j$.isFunction_(result.message)) { - return result.message(); - } else { - return result.message; - } - } - - args = args.slice(); - args.unshift(true); - args.unshift(matcherName); - return util.buildFailureMessage.apply(null, args); - } - }; - - - function ContextAddingFilter(message) { - this.message = message; - } - - ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { - return this.message + ': ' + msg; - }; - - return AsyncExpectation; -}; diff --git a/src/core/Env.js b/src/core/Env.js index a5f6c4df..3b9c2b97 100644 --- a/src/core/Env.js +++ b/src/core/Env.js @@ -193,7 +193,7 @@ getJasmineRequireObj().Env = function(j$) { }; j$.Expectation.addCoreMatchers(j$.matchers); - j$.AsyncExpectation.addCoreMatchers(j$.asyncMatchers); + j$.Expectation.addAsyncCoreMatchers(j$.asyncMatchers); var nextSpecId = 0; var getNextSpecId = function() { @@ -206,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, @@ -220,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 e6b6fc70..34f777a4 100644 --- a/src/core/Expectation.js +++ b/src/core/Expectation.js @@ -1,139 +1,133 @@ 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.filters = new j$.ExpectationFilterChain(); + this.expector = new j$.Expector(options); var customMatchers = options.customMatchers || {}; for (var matcherName in customMatchers) { - this[matcherName] = wrapCompare(matcherName, customMatchers[matcherName]); + this[matcherName] = wrapSyncCompare(matcherName, customMatchers[matcherName]); } } - function wrapCompare(name, matcherFactory) { + Expectation.prototype.withContext = function withContext(message) { + return addFilter(this, new ContextAddingFilter(message)); + }; + + 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 args = Array.prototype.slice.call(arguments, 0), - expected = args.slice(0); - - args.unshift(this.actual); - - var matcherCompare = this.instantiateMatcher(matcherFactory); - var result = matcherCompare.apply(null, args); - this.processResult(result, name, expected, args); + var result = this.expector.compare(name, matcherFactory, arguments); + this.expector.processResult(result); }; } - Expectation.prototype.instantiateMatcher = function(matcherFactory) { - var matcher = matcherFactory(this.util, this.customEqualityTesters); - var comparisonFunc = this.filters.selectComparisonFunc(matcher); - return comparisonFunc || matcher.compare; - }; + function wrapAsyncCompare(name, matcherFactory) { + return function() { + var self = this; - Expectation.prototype.processResult = function(result, name, expected, args) { - var message = this.buildMessage(result, name, args); + // 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(); - if (expected.length === 1) { - expected = expected[0]; + 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); } + } - 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 - } - ); - }; + function addFilter(source, filter) { + var result = Object.create(source); + result.expector = source.expector.addFilter(filter); + return result; + } - Expectation.prototype.buildMessage = function(result, name, args) { - var util = this.util; - - if (result.pass) { - return ''; - } - - var msg = this.filters.buildFailureMessage(result, name, args, util, defaultMessage); - return this.filters.modifyFailureMessage(msg || defaultMessage()); - - function defaultMessage() { - if (!result.message) { - args = args.slice(); - args.unshift(false); - args.unshift(name); - return util.buildFailureMessage.apply(null, args); - } else if (j$.isFunction_(result.message)) { + function negatedFailureMessage(result, matcherName, args, util) { + if (result.message) { + if (j$.isFunction_(result.message)) { return result.message(); } else { return result.message; } } - }; - Expectation.prototype.addFilter = function(filter) { - var result = Object.create(this); - result.filters = this.filters.addFilter(filter); + args = args.slice(); + args.unshift(true); + args.unshift(matcherName); + return util.buildFailureMessage.apply(null, args); + } + + function negate(result) { + result.pass = !result.pass; return result; - }; + } - Expectation.addCoreMatchers = function(matchers) { - var prototype = Expectation.prototype; - for (var matcherName in matchers) { - var matcher = matchers[matcherName]; - prototype[matcherName] = wrapCompare(matcherName, matcher); - } - }; - - Expectation.Factory = function(options) { - var expect = new Expectation(options || {}); - expect.not = expect.addFilter(negatingFilter); - - expect.withContext = function(message) { - var result = this.addFilter(new ContextAddingFilter(message)); - result.not = result.addFilter(negatingFilter); - return result; - }; - - return expect; - }; - - - var negatingFilter = { + var syncNegatingFilter = { selectComparisonFunc: function(matcher) { function defaultNegativeCompare() { - var result = matcher.compare.apply(null, arguments); - result.pass = !result.pass; - return result; + return negate(matcher.compare.apply(null, arguments)); } return matcher.negativeCompare || defaultNegativeCompare; }, - buildFailureMessage: function(result, matcherName, args, util) { - if (result.message) { - if (j$.isFunction_(result.message)) { - return result.message(); - } else { - return result.message; - } - } - - args = args.slice(); - args.unshift(true); - args.unshift(matcherName); - return util.buildFailureMessage.apply(null, args); - } + 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; @@ -143,5 +137,18 @@ getJasmineRequireObj().Expectation = function(j$) { return this.message + ': ' + msg; }; - return Expectation; + 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); + } + }; }; 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/requireCore.js b/src/core/requireCore.js index 181c2c32..8ff7448b 100644 --- a/src/core/requireCore.js +++ b/src/core/requireCore.js @@ -38,8 +38,8 @@ var getJasmineRequireObj = (function (jasmineGlobal) { j$.StackTrace = jRequire.StackTrace(j$); j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); j$.ExpectationFilterChain = jRequire.ExpectationFilterChain(); + j$.Expector = jRequire.Expector(j$); j$.Expectation = jRequire.Expectation(j$); - j$.AsyncExpectation = jRequire.AsyncExpectation(j$); j$.buildExpectationResult = jRequire.buildExpectationResult(); j$.JsApiReporter = jRequire.JsApiReporter(); j$.matchersUtil = jRequire.matchersUtil(j$);