A mock framework for JavaScript in the spirit of RR.
To run the tests, build the dist/jj.js file by running rake dist
.
Sample object:
var item = { foo: function() { return “FOO”; }, bar: function() { return “BAR”; } } item.foo(); // => “FOO” item.bar(); // => “BAR”If you just want to stub a method that’s already been defined for
the target object, you can use the most concise form of JJ stub
declaration, which is just calling returns
on the stubbed method,
passing the value you’d like returned:
The syntax for stubbing methods that are not defined on the target
object is more verbose, though not by much. Call method
on the stub
proxy, passing the name of the method you’d like to stub. Then call
returns
on that.
Note that you can also use this style for stubbing methods are defined
on the target object. I just don’t think it’s as pretty.
To reset an object, just call JJ.reset
and pass the object.
In an attempt to get the kind of dynamic stub declaration that RR
provides, I’m working on “stub contexts” for JJ, where you pass a
function as the second argument to the JJ.stub
call. Within there,
you can stub methods that may or may not actually be implemented in
the target object:
Note that this feature is still a bit buggy. Use with caution.
Big credit should go to Brian Takita for creating RR, the best
doggone’ test double framework there ever were.
To use JJ with Screw.Unit, make sure you’re using Brian’s recent branch
that passes the screwContext
into your tests. Then, in an after block,
add JJ.verify(screw)
:
Screw.Unit(function(screw) { with(screw) { describe("JJ", function() { var item; before(function() { JJ.reset(); item = { foo: "FOO!" }; }); it("receives foo", function() { JJ.mock(item).foo.returns("FOO!"); }); after(function() { JJ.verify(screw); JJ.reset(); }); }); }});
You can also set how many times the method should be called:
JJ.mock(item).foo.times(3);This will make your test only pass when the foo
method gets
called 3 times on item
. If you don’t specify a specific number,
then your test will pass as long as the method was called at least once.
- Code cleanup. Big time.
- Mocks
- argument awareness
- Probes
- Integration with Screw.Unit
- Spies
© Copyright 2008 Pat Nakajima, released under MIT License.