Jack is a toolkit for mocking JavaScript objects and functions when writing tests. It is inspired by similar projects for Java and C#, like JMock, Mockito and Rhino Mocks
Mocking can be achieved quite easily in JavaScript without help from a library, but anything above verifying that a function gets called can grow hard to read. If you have experienced this (or want to avoid it in the first place), Jack is for you.
Contributions are very welcome. Just fork git://github.com/keronsen/jack.git and get started.
The head developer for Jack is Karl-Erik Rønsen
Contributions have been received, accepted and appreciated from:
Download the latest version of Jack from github: http://github.com/keronsen/jack
General examples are found below.
There are examples of use with different test frameworks in /docs/examples.
If you need help, there is a google group for discussion: http://groups.google.com/group/jack-discuss
Jack is currently compatible with these JavaScript test frameworks:
- JsTestDriver
- QUnit
- YUI Test
- JSSpec (Also used for testing Jack itself)
- Scriptaculous TestRunner
Integration is planned for these frameworks:
For these examples, the application under test has a function storeSomething() that we expect will call the jQuery.post() function.
jack(function(){
jack.expect("jQuery.post").exactly("1 time");
storeSomething();
});
Available call quantifiers: never(), once(), exactly(), atLeast(), atMost()
jack(function(){
jack.expect("jQuery.post")
.exactly("1 time")
.withArguments("http://example.com/service");
storeSomething();
});
jack(function(){
jack.expect("jQuery.post")
.exactly("1 time")
.whereArgument(0).isOneOf("/serviceOne","/serviceTwo");
storeSomething();
});
Available constraint methods: is(), isNot(), isOneOf(), isType(), matches(), hasProperty(), hasProperties()
jack(function(){
jack.expect("jQuery.post")
.exactly("1 time")
.mock(function() {
// your mock implementation
});
storeSomething();
});
jack(function(){
jack.expect("jQuery.post")
.exactly("1 time")
.returnValue("The value to return.");
storeSomething();
});
If you want to test how your code under test interacts with other objects, you can create a mock object with jack.create()
:
jack(function(){
var myStack = jack.create("myStack", ['push','pop']);
jack.expect("myStack.push")
.exactly("1 time")
.whereArgument(0).is("something");
useTheStack(myStack);
});