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 {
             thenReturn:function(arg1){
                 stub.configureOutput(arg1);
             }
           };
       }
       function stub(actual){
         var expectedArgs,
             configuredOutput,
             isConfigured = false;
         actual.configureOutput = function(output){
             configuredOutput = output;
             isConfigured = true;
         }
         actual.someMethod = function(){
             if (isConfigured){
                if (expectedArgs[0] == arguments[0])
                   return configuredOutput;
                return;
             }
             else
                expectedArgs = arguments;
             return actual;
         };
         return actual;
       }

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

        when(theStub.someMethod(2)).thenReturn(5);
        expect(theStub.someMethod(2)).toBe(5);
    });
});

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.