Allow adding custom spy strategies

[#37288941]
This commit is contained in:
Steve Gravrock
2018-01-10 08:41:47 -08:00
parent 1085914a76
commit 4934e420b2
7 changed files with 217 additions and 12 deletions

View File

@@ -108,6 +108,13 @@ getJasmineRequireObj().Env = function(j$) {
return true;
};
this.addSpyStrategy = function(name, fn) {
if(!currentRunnable()) {
throw new Error('Custom spy strategies must be added in a before function or a spec');
}
runnableResources[currentRunnable().id].customSpyStrategies[name] = fn;
};
this.addCustomEqualityTester = function(tester) {
if(!currentRunnable()) {
throw new Error('Custom Equalities must be added in a before function or a spec');
@@ -152,7 +159,7 @@ getJasmineRequireObj().Env = function(j$) {
};
var defaultResourcesForRunnable = function(id, parentRunnableId) {
var resources = {spies: [], customEqualityTesters: [], customMatchers: {}};
var resources = {spies: [], customEqualityTesters: [], customMatchers: {}, customSpyStrategies: {}};
if(runnableResources[parentRunnableId]){
resources.customEqualityTesters = j$.util.clone(runnableResources[parentRunnableId].customEqualityTesters);
@@ -393,7 +400,15 @@ getJasmineRequireObj().Env = function(j$) {
reporter.clearReporters();
};
var spyFactory = new j$.SpyFactory();
var spyFactory = new j$.SpyFactory(function() {
var runnable = currentRunnable();
if (runnable) {
return runnableResources[runnable.id].customSpyStrategies;
}
return {};
});
var spyRegistry = new j$.SpyRegistry({
currentSpies: function() {

View File

@@ -13,7 +13,7 @@ getJasmineRequireObj().Spy = function (j$) {
* @constructor
* @name Spy
*/
function Spy(name, originalFn) {
function Spy(name, originalFn, customStrategies) {
var numArgs = (typeof originalFn === 'function' ? originalFn.length : 0),
wrapper = makeFunc(numArgs, function () {
return spy.apply(this, Array.prototype.slice.call(arguments));
@@ -23,7 +23,8 @@ getJasmineRequireObj().Spy = function (j$) {
fn: originalFn,
getSpy: function () {
return wrapper;
}
},
customStrategies: customStrategies
}),
callTracker = new j$.CallTracker(),
spy = function () {

View File

@@ -1,10 +1,10 @@
getJasmineRequireObj().SpyFactory = function(j$) {
function SpyFactory() {
function SpyFactory(getCustomStrategies) {
var self = this;
this.createSpy = function(name, originalFn) {
return j$.Spy(name, originalFn);
return j$.Spy(name, originalFn, getCustomStrategies());
};
this.createSpyObj = function(baseName, methodNames) {

View File

@@ -16,6 +16,22 @@ getJasmineRequireObj().SpyStrategy = function(j$) {
this.originalFn = options.fn || function() {};
this.getSpy = options.getSpy || function() {};
this.plan = this._defaultPlan = function() {};
var k, cs = options.customStrategies || {};
for (k in cs) {
if (j$.util.has(cs, k) && !this[k]) {
this[k] = function() {
var plan = cs[k].apply(null, arguments);
if (!j$.isFunction_(plan)) {
throw new Error('Spy strategy must return a function');
}
this.plan = plan;
return this.getSpy();
};
}
}
}
/**