JavascriptUnitTesting/MockIo

Not logged in - Log In / Register

Revision 1 as of 2011-08-26 09:00:01

Clear message

MockIo library

MockIo is a simple library to help you test code that does Y.io calls by intercepting those calls and providing a server response of your own.

Files and namespaces

MockiIo is found in lib/lp/app/testing/mockio.js and its namespace is Y.lp.testing.mockio. The instrumentation helpers are in Y.lp.client because it needs to be usable by production code.

Instrumentation

Before you can test your code you need to instrument it to intercept Y.io calls. This is done by passing an extra argument to the function or adding an attribute to an objects config. By convention this parameter is called io_provider because it provides a replacement io method. During test you pass in an instance of MockIo via this parameter, in production you just leave it undefined (or pass in Y).

Here is an example for a class.

var MyClass = function(config) {
    this.io_provider = Y.lp.client.get_configured_io_provider(config);
};

MyClass.prototype.do_something() {

    // Some code that prepares an url and a io_config for an xhr request.

    // This is where Y.io used to be called.
    this.io_provider.io(url, io_config);
};

Here is an example for a simple function.

var myfunc = function(param1, param2, io_provider) {

    // Some code that prepares an url and a io_config for an xhr request.

    // This is where Y.io used to be called.
    Y.lp.client.get_io_provider(io_provider).io(url, io_config);
};

Mocking io calls in tests

Mocking happens in three steps.

  1. Create the MockIo instance.

  2. Pass it to your instrumented code.
  3. Prepare and send a response.

more text