Skip to content

Instantly share code, notes, and snippets.

@dbalduini
Last active April 26, 2021 14:05
Show Gist options
  • Save dbalduini/5c80035b69650262962701a57c0102ca to your computer and use it in GitHub Desktop.
Save dbalduini/5c80035b69650262962701a57c0102ca to your computer and use it in GitHub Desktop.
JQuery stub and mock with Sinon for Unit Tests
(function () {
'use strict';
var sinon = require('sinon');
var keys = ['closest', 'addClass', 'children', 'parent', 'find', 'html',
'remove', 'text', 'ready', 'unveil', 'removeAttr', 'removeClass', 'scroll',
'val', 'height', 'css', 'delay', 'queue', 'dequeue', 'attr'];
function JQueryStub (args) {
var self = this;
// Stub jquery methods
keys.forEach(function (k) {
self[k] = sinon.stub();
});
// add self reference to allow call chain
Object.keys(self).forEach(function (key) {
self[key].returns(self);
});
self.args = args;
return self;
}
JQueryStub.prototype.reset = function () {
var self = this;
Object.keys(self).forEach(function (key) {
if (keys.indexOf(key) !== -1) {
self[key].reset();
}
});
};
function Mock () {
var self = this;
self.currentIndex = 0;
self.callCache = [];
// Set global jQuery
if (global.$) {
self.original = global.$;
}
global.$ = function () {
var args = Array.prototype.slice.call(arguments);
var stub;
if (self.callCache[self.currentIndex]) {
stub = self.callCache[self.currentIndex];
stub.args = args;
} else {
stub = new JQueryStub(args);
self.callCache.push(stub);
}
self.currentIndex++;
return stub;
};
return this;
}
Mock.prototype.getCall = function (n) {
return this.callCache[n];
};
Mock.prototype.onCall = function (n) {
var stub = new JQueryStub();
this.callCache[n] = stub;
return stub;
};
Mock.prototype.resetAll = function () {
this.currentIndex = 0;
this.callCache = [];
};
Mock.prototype.restore = function () {
if (this.original) {
global.$ = this.original;
} else {
delete global.$;
}
};
module.exports = {
Mock : Mock
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment