Fluent API for test doubles

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:

  1.  
  2. describe("a fluent API to create a test stub", function(){
  3. it("stubs out a method", function(){
  4. // the fluent API:
  5. function when(stub){
  6. return {
  7. thenReturn:function(arg1){
  8. stub.configureOutput(arg1);
  9. }
  10. };
  11. }
  12. function stub(actual){
  13. var expectedArgs,
  14. configuredOutput,
  15. isConfigured = false;
  16. actual.configureOutput = function(output){
  17. configuredOutput = output;
  18. isConfigured = true;
  19. }
  20. actual.someMethod = function(){
  21. if (isConfigured){
  22. if (expectedArgs[0] == arguments[0])
  23. return configuredOutput;
  24. return;
  25. }
  26. else
  27. expectedArgs = arguments;
  28. return actual;
  29. };
  30. return actual;
  31. }
  32.  
  33. // the test confirming it works:
  34. var actualObject = {someMethod: function(a){return 1+a;}};
  35. var theStub = stub(actualObject);
  36.  
  37. when(theStub.someMethod(2)).thenReturn(5);
  38. expect(theStub.someMethod(2)).toBe(5);
  39. });
  40. });
  41.  

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.

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.