API Introduction
Welcome to the API documentation for qMock. Like it says on the tin, this page only lists the available methods for instantiated mock objects, with basic examples only. There is an accompanying 'Patterns' section (TODO) which aim to gather together mocking code for common JavaScript scenarios (e.g. Ajax requests), as well as a 'Learn' section (TODO) for more information about mocking, integration testing, and where it fits in regarding TDD.
There are three main sections to the API docs, the first gives a high-level overview of a typical Mock object, along with its children 'Mocked Member' objects. The second section details the API for the paren, and the third focuses on the Mock Member object interface. Happy mocking!
High-level overview of a Mock Object
>>>>>>>>>> Insert Diagram <<<<<<<<<<<<<<<<<
Mock (Constructor function)
Mock instances are created from the global Mock object:
var myMock = Mock();
//
var myMock = new Mock(); // personal preference for readability.
- Mock() returns a new Mock object with various public methods available to set expected interactions upon it.
- In the context of testrunners such as QUnit or YUI, this is normally done in the 'setup' or 'before' phase of a test case.
Mock Object Interface
- expects
- expectsArguments
- verify
- reset
expects( min, max )
Instantiates new mock method object (child mock object), and sets expected invocation boundaries on method mock.
@param {Number} min Minimum number of invocations of mocked method (Defaults to 0) -- Optional.
@param {Number} max Maximum number of invocations of mocked method (Defaults to false) -- Optional.
@returns {MockedMethod object} (see Method Object Interface)
// explict execution call total
var ninja = new Mock();
ninja
.expects(1)
.method('swing');
// arbitrary execution call total
var samurai = new Mock();
samurai
.expects(60, 200)
.method('hide'); // In between 60 and 200 invocations, inclusive.
// No more than n
var wizard = new Mock();
samurai
.expects(0, 50)
.method('magic'); // Up to 50 invocations
// At least n
var samurai = new Mock();
samurai
.expects(50, Infinity) // Allow any number of calls
.method('hide'); // 50 or more invocations, no upper limit, raise as necessary.
Notes:
- Defaults to expecting zero calls explicitly if no arguments supplied.
- If min supplied, mock will expect exactly that number of invocations of the mocked method.
- If max supplied, mock will expect that number of invocations of mocked method to be between min and max inclusive.
- max argument can be overloaded with the special Infinity object to provide an infinite upper boundary for the range (See example above).
expectsArguments ( Object ) overload
Sets arguments expected by a Mock object instance.
@param {Objects} Object Accepts any number of objects, of any type, in the standard parameter passing convention.
@returns the Mock object instance, to allow for further expected behaviour definitions.
// single argument
var ninja = new Mock();
ninja
.expectsArguments("Jet Li");
// multiple arguments
var samurai = new Mock();
samurai
.expectsArguments("name", Katana);
Notes:
- Normally called after the initial mock instantiation. Allows a mock object to act as a constructor.
- Arguments are stored internally and compared against actual (inc. deep comparisons of arrays and object literal member elements).
verify
Compares the actual behaviour of the mock against the expected behaviour, checking the Mock object itself, then the bound Mock Method Objects comprising the interface respectively.
@returns {Boolean}
@errors {InvalidConstructorException // IncorrectNumberOfArgumentsException // IncorrectNumberOfMethodCallsException}
// QUnit
ok(mock.verify(), "verify() should be true");
// YUI
YAHOO.util.Assert.isTrue(mock.verify(), "verify() should be true");
Notes:
- Used in conjunction with some kind of assert statement to test whether the mock was successfully interacted with.
reset
Resets the mock to it's original state before the exercise phase.
// Setup
// Exercise
// Verify
mock.reset();
Notes:
- Can be used in the teardown phase of a testrunner, to ensure that previous test results do not persist after they finish.
Mocked Method Object Interface
- method
- atLeast
- noMoreThan
- withArguments
- property
- withValue
- andReturn
- andChain
- callFunctionWith
- andExpects
Mocks can have either methods or properties defined on them, just like any other object in JavaScript.
method( name )
Sets the name of the method, as well as the public identifier for it on the mock object.
@param {String} name Name of the method. Used to set the method publicly on the mock.
@error {InvalidMethodNameException} If attempt to overwrite an existing Mock object member.
@returns the bound Mock Method instance, to allow for further expected behaviour definitions.
var ninja = new Mock();
ninja
.expects(1)
.method('swing');
console.log(ninja.swing.constructor === Function) // >>> true
Notes:
- Usually called directly after the Mock object expects method.
atLeast( min )
Sets the minimum amount of times a Mocked Method instance expects to be invoked.
@param {Number} min
var ninja = new Mock();
ninja
.expects()
.method('swing')
.atLeast(3);
noMoreThan( max )
Sets the maximum amount of times a Mocked Method instance expects to be invoked.
@param {Number} max
var ninja = new Mock();
ninja
.expects()
.method('swing')
.noMoreThan(3);
// defining a range of invocations
var samurai = new Mock();
samurai
.expects()
.method('swing')
.atLeast(1)
.noMoreThan(3);
// shorthand version
var samurai = new Mock();
samurai
.expects(1,3)
.method('swing');
withArguments( Object ) overload
Sets arguments expected by a Mocked Method instance (returned by expects).
@param {Objects} Object Accepts any number of objects, of any type, in the standard parameter passing convention.
@returns the bound Mock Method instance, to allow for further expected behaviour definitions.
// single argument
var ninja = new Mock();
ninja
.expects(1)
.method('swing')
.withArguments('hard');
// multiple arguments
var samurai = new Mock();
samurai
.expects(1)
.method('fight')
.withArguments({
foe: ninja,
weapon: "sword"
}, 100);
Notes:
- Normally called upon the object returned by expects.
- Arguments are stored internally and compared against actual (inc. deep comparisons of arrays and object literal member elements).
property( name )
Sets the name of a property, as well as the public identifier for it on the mock object.
@param {String} name Name of the property. Used to set the property publicly on the mock.
@error {InvalidPropertyNameException} If attempt to overwrite an existing Mock object member.
@returns the bound Mock Method instance, to allow for further expected behaviour definitions.
var mock$ = new Mock();
mock$
.expects(1)
.property('browser');
console.log(ninja.browser === "stub") // >>> true
Notes:
- Good for defining constants or stubs in an explicit manner. Although this could be done manually, this technique explicitly defines to other developers what Mock object members will be accessed.
- Default value is "stub".
withValue( value ) [overload]
Sets the value of a stubbed property (see abovementioned property method).
@param {Object} value Value of the stubbed property.
@returns the bound Mock Method instance, to allow for further expected behaviour definitions.
var mock$ = new Mock();
$
.expects(1)
.property('browser')
.withValue({
msie: false,
mozilla: false,
chrome: true
});
console.log(ninja.browser.chrome === true) // >>> true
andReturn( stub )
Sets the return value of the bound Mock Method object, also known as a stub.
@param {Object} stub Object of any type returned when method is invoked.
var ninja = new Mock();
ninja
.expects(1)
.method('swing')
.withArguments('hard')
.andReturn('hit');
Notes:
- Method usually denotes the end of a mock method definition, and can be followed by andExpects method to start a new mock method definition (See below for docs).
andChain
Sets the return value of the bound Mock Method object to be the Mock object (parent), and facilitate cascade-style programming (chaining) in the exercise phase.
var ninja = new Mock();
ninja
.expects(1)
.method('swing')
.withArguments('hard')
.andChain();
callFunctionWith( Object ) [overload]
Sets the arguments to be passed to any callback function defined by withArguments.
@param {Object} Object Accepts any number of objects, of any type, in the standard parameter passing convention.
mock$ = new Mock();
mock$
.expects(1)
.method('get')
.withArguments('some/url', Function)
.callFunctionWith('data response');
// Exercise
var called = false;
mock$.get('some/url', function (data) { called = true });
Notes:
- This pattern is most used for Ajax requests, where an onSuccess/onFail callback is passed in and often bound to a particular DOM/Object reference, or is setup to receive data from the server.
- This method lets us stub the response of the server to the callback, without overwriting the Mock Method object's own return value.
- The callback could be a 'real' implementation, or a mock in it's own right.
andExpects
Facade for expects, also returns a new mocked method instance. See expects docs abovementioned for details.
var ninja = new Mock();
ninja
.expects(1)
.method('swing')
.withArguments('hard')
.andReturn('hit')
.andExpects()
.method('duck')
.noMoreThan(10);
Pass-through Arguments
The objects Variable & Selector or EventObject can be used to denote an argument that is unknown in advance, or of variable nature.
var mock$ = new Mock();
mock$
.expectsArguments(Selector);
// Custom pass-through types
window.JSON = Variable;
console.log(JSON.constructor === Variable); // >>> true
Note:
- Can define own pass-through argument object types by assigning either Variable or Selector to a global variable(s) with your own naming convention.