Skip to content

Instantly share code, notes, and snippets.

@subtubes-io
Created April 17, 2014 06:47
Show Gist options
  • Select an option

  • Save subtubes-io/10958636 to your computer and use it in GitHub Desktop.

Select an option

Save subtubes-io/10958636 to your computer and use it in GitHub Desktop.
JavaScripot Spy Class for 3rd party testing frameworks
(function () {
window.EhSpy = function (suspect, methodName) {
var self = this;
self.original = suspect[methodName];
suspect[methodName] = function () {
self.wasCalled = true;
self.reset();
};
self.reset = function () {
suspect[methodName] = self.original;
};
self.hasBeenCalled = function () {
return self.wasCalled;
}
};
}())
(function () {
describe("SpyClass", function () {
it("Should overwrite the original object function", function () {
var suspect = {
func: function () {
return "hello world";
}
};
var original = suspect.func;
var mySpy = new EhSpy(suspect, "func");
expect(original.toString()).not.toEqual(suspect.func.toString());
});
it("Should reset the original value of calling reset", function () {
var suspect = {
func: function () {
return "hello world";
}
};
var original = suspect.func;
var mySpy = new EhSpy(suspect, "func");
mySpy.reset();
expect(original.toString()).toEqual(suspect.func.toString());
});
it("Should reset the function value after it has been spied on", function() {
var suspect = {
func: function () {
return "hello world";
}
};
var original = suspect.func;
var mySpy = new EhSpy(suspect, "func");
suspect.func();
expect(original.toString()).toEqual(suspect.func.toString());
});
it("Should return wasCalled when hasBeenCalled is invoked", function () {
var suspect = {
func: function () {
return "hello world";
}
};
var original = suspect.func;
var mySpy = new EhSpy(suspect, "func");
suspect.func();
expect(mySpy.hasBeenCalled()).toEqual(true);
});
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment