Creating Stubs

This example is based on Examples/Source/Mocks and Stubs/Stubs.Dependencies.js and Examples/Tests/Mocks and Stubs/StubTests.js from

Often, code we are testing will consume complex objects, interfaces or hierarchies. These contracts can be fulfilled with lightweight structures called Stubs. xUnit.js provides a mechanism for quickly creating stubs with well-known shapes and outputs, as well as providing instrumentation recording invocations, arguments and return values.


function openResults(targetWindow){ var resultsWindow ="results/url"); return resultsWindow; }


Function.RegisterNamespace("Test"); [Import("../../Source/Mocks and Stubs/Stubs.Dependencies.js")] [Fixture] Test.StubTests=function(){ [Fact] function ReturnsResultWindowHandle(){ var expected="expected"; var windowStub=Stubs.GetObject( {open:{returnValue:expected}}, {location:"known/url"} ); var actual=openResults(windowStub); Assert.Equal(expected, actual); } }

Above, we can see that our openResults() method expects a window object with an open() method that returns a result.

Since we don't have access to a true window object in our test, we can create a Stub with the required shape, and specify a known value as the result for our expectation.

Stubs.GetObject(methods,properties) accepts two parameters, an object map of public methods to create, and an object map of public properties to assign to the resulting stub.

Methods can take the shape of a natural javascript method, i.e. {method:function(parameter1, parameter2){return "returnValue";}} - in which case the method body will be executed - or the shape of an object map with an optional array of parameters and an optional returnValue, i.e. {method:{parameters:["parameter1","parameter2"],returnValue:"returnValue"}};