JSocka is a library for stubbing methods and parameters in Javascript. It strives to replicate Mocha syntax, which in turn uses a JMock-like syntax.
JSocka is designed to be test-framework-agnostic, though the test specs for the code itself are written in JSpec. JSocka also includes an integration module for JSpec, which provides alternative syntax.
For more information regarding the JSpec testing framework, please visit github.com/visionmedia/jspec/tree/master
In order to start using JSocka, all you need to do is include the lib/jsocka.js Javascript file.
Here are some usage examples
JSocka("Person").stubs("speak").returns("function(){alert('I love stubbing')}); // Person.speak() now calls the stubbed function JSocka("Person").any_instance.stubs("speak").returns("function(){alert('I love stubbing')}); // p = Person.new // p.speak() now calls the stubbed function JSocka("Person").expects("speak"); JSocka("Person").expects("speak").never(); JSocka("Person").expects("speak").returns("function(){alert('I love stubbing')}); JSocka.clearStubs(); // This clears out all existing stubs, and resets the original functions
Please note that every JSocka method is a function, not a parameter. While Mocha does support some syntax like Person.expects(method).once, there’s not a way to implement this in Javascript. Everything needs parentheses! The only exception to this is when using JSocka(“Object”).any_instance.stubs()
Expectations are destructive (Adding hook code with chaining doesn’t work for base classes). Be aware that JSocka(“Person”).expects(“speak”) will keep track of how many times the Person.speak method is called, but Person.speak will not return anything unless you explicitly define it, i.e. JSocka(“Person”).expects(“speak”).returns(“function(){ // code}”)
The modules/jspec.jsocka.js file is a module that extends JSpec functionality. This includes:
-
New Object.stubs syntax, instead of JSocka(“Object”).stubs. This works with expects and any_instance as well.
-
Automatic expectation-checking and destubbing after every spec. For example, the following spec will automatically fail:
describe "Example" it "should fail" Object.expects("my_method") end end
JSpec will automatically hook into the errors collection and display them with the test.
-
Changes for each version noted in the History.rdoc file.
-
All bugs & features are managed using PivotalTracker, and can be viewed at www.pivotaltracker.com/projects/24351
Please feel free to contact me with questions or suggestions at kevin.gisi@gmail.com