MockMe: A new JavaScript mocking framework
Written by on August 11th, 2008 in Uncategorized.
Johannes Link is an Agile fellow who wasn’t 100% happy with the existing JavaScript unit test frameworks, and he explained why. He gives an example:
JAVASCRIPT:
-
-
testDoubleSpeaker: function() { with(this) {
-
var actualMsg = null;
-
var mockSay = function(msg) {
-
actualMsg = msg;
-
};
-
Speaker.say = mockSay;
-
DoubleSpeaker.say(‘oops’);
-
assertEqual(‘oopsoops’, actualMsg);
-
}}
-
It works, but he discusses how this changes the global world, which is a bad thing. Would it be nicer to spy and end up with:
JAVASCRIPT:
-
-
testDoubleSpeaker: function() { with(this) {
-
mock(Speaker).andDo(function() {
-
DoubleSpeaker.say(‘oops’);
-
verify(Speaker.say)(‘oopsoops’);
-
});
-
}},
-
This is an example from his new framework, MockMe, which has the main features:
- The basic granularity of mocking should be the function. If I want to, I can fake the behaviour of a single function without influencing the rest (of an object or a prototype or the global namespace or whatever).
- Most of the time, spying is a better idea than mocking because it’s simpler. Spying basically means that, instead of specifying the expected interaction with your mock spy object before doing the test, you use the mock spy object to spy into the interaction as it happens and verify that afterwards. In that respect I borrowed heavily from mockito, a spying framework that’s gaining more and more attention in the Java world.
A few other examples:
JAVASCRIPT:
-
-
when(f)(‘in’).thenReturn(‘out’);
-
assertEqual(‘out’, f(‘in’));
-
-
when(f)({name: ‘hello’}).thenReturn(‘yeah’);
-
assertEqual(‘yeah’, f({name: ‘hello’}));
-
-
when(f)(any()).thenReturn(‘yeah’);
-
assertEqual(‘yeah’, f(1));
-
-
verify(times(2), f)(1); //succeeds
-
useMockerFor(function(mocker)) {
-
mocker.within(MyObject).mock(‘f1′);
-
when(MyObject.f1)().thenReturn(5);
-
assertEqual(7, MyObject.f2());
-
} // Here everything you mocked will automatically be restored
-
-
assertEqual(3, MyObject.f2());
-
Source: Ajaxian » Front Page
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/361939856/mockme-a-new-javascript-mocking-framework