Spying on Titanium; Titanium Appcelerator and Jasmine.

I've now worked small parts in a couple of Appcelerator projects for iOS. Both times I have been tasked with improving the unit testing.

Jasmine from Pivotal is a great Javascript unit testing framework, (https://github.com/pivotal/jasmine/wiki), and has been modified to work with with the Titanium framework (https://github.com/guilhermechapiewski/titanium-jasmine).

It mostly works excellently with all of Jasmine's features are available. The only issue I had was not being able spy on objects and methods that are a part of the Titanium API.

One way to get around this is to replace the part of the API you intend to use with a stubbed version. Say for example that you wish to spy on Titanium.Network.createHTTPClient. Before exercising any production code that uses it do something like:

It is then possible to call spyOn(Titanium.Network, "createHTTPClient") and subsequently expect this to have been called. Once done Titanium.Network can be set back to originalTiNet if required.

The same can be done for objects returned by Titanium's create methods. Either get your stubbed API (Titanium.Network in this case) to return a stubbed object, or use a spy to do it as in the below example. 

In this case we want to be able to verify that send and open were called on an HttpClient object. By setting up the above (in addition to the first gist) every subsequent call to Titanium.Network.createHTTPClient in our production code will be given stubClient, and we can verify calls made to send and open.

If anyone is interested I can post up a more complete example.