Mocking Objects with Sinon JS

We recently started writing a mobile website using JavaScript as our framework. To test the JavaScript framework we decided to try Sinon and Jasmine .

With Sinon a mock is created from an instance of an object. Needing to create an instance of a class to make a mock becomes difficult for classes that have complex initialization.

1
2
3
4
5
  ClassToTest = function() { ... };
 
  bar = new ClassToTest();
  barMock = sinon.mock(bar);
  barMock.expects("baz")

If our ClassToTest had a complex initialization our test would have to account for that. We were able to get around the initialize by creating an empty function and updating its prototype.

1
2
3
4
5
6
7
8
  ClassToTest = function()   {
    this.x = SomethingComplex.buildIt();
  };
  
  Foo = function() {}; 
  Foo.prototype = ClassToTest.prototype;
  foo = new Foo;
  fooMock = sinon.mock(foo);

In this example our class Foo would have all the functions of our ClassToTest. Which makes Sinon happy. When we create a new Foo the ClassToTest initialize does not run which makes our tests happy.