There are several good frameworks out there to create test doubles with JavaScript. Jasmine  and Sinon provide test spies and stubs. JsMockito looks good too. However, creating your own API for test stubs is very easy. I’ve created mine as an exercise. It’s a very naive implementation but it works. See the code:

describe("a fluent API to create a test stub", function(){
  it("stubs out a method", function(){
       // the fluent API:
       function when(stub){
           return {
       function stub(actual){
         var expectedArgs,
             isConfigured = false;
         actual.configureOutput = function(output){
             configuredOutput = output;
             isConfigured = true;
         actual.someMethod = function(){
             if (isConfigured){
                if (expectedArgs[0] == arguments[0])
                   return configuredOutput;
                expectedArgs = arguments;
             return actual;
         return actual;

       // the test confirming it works:
        var actualObject = {someMethod: function(a){return 1+a;}};
        var theStub = stub(actualObject);


The implementation is not generalized to support any method or any number of parameters. I just wanted to play with the idea that I can invoke the stubbed method in the “when” statement and it doesn’t execute anything apparently. It only executes the stubbed behavior once it’s been configured.

It’s very simple but it didn’t come up to my mind when I implemented pyDoubles (now Doublex), which might have made the API even better.