Wednesday 20 June 2012

Testable client side view model with knockout without any server side dependencies

After reading the blog post series looking at creating a testable application with a JavaScript by Peter Vogel which looked at setting up the server side and the client side view model using Knockout I couldn’t help but think JavaScript needs a way of doing a kind of dependency injection so it can be unit testable without the reliance on the server side.

I understand that it will have a reliance on the server side to output the tests, however this is down to the implementation of the project not a requirement of unit testing.

View model creation

The view model is setup in a very similar way to how Peter had it in his example with a couple of tweaks to allow for the “DI” to function.

var Customer = function () {
    this.CustId = ko.observable();
    this.CompanyName = ko.observable();
    this.City = ko.observable();

    var self = this;

    this.getCustomer = function (custId) {

        MyApp.Customer.getCustomer(custId, this.updateData);

    };

    this.updateData = function (data) {
        self.CustId(data.CustomerID);
        self.CompanyName(data.CompanyName);
        self.City(data.City);
    };
}

We start by setting up the properties of the view model with the Knockout observables, set a reference to it’s self to be able to reference them later (good practice with Knockout from what I can gather), a callback binding function and the first “action” function on the model; getCustomer.

The getCustomer method calls into the data service passing in the parameters it requires for the action to execute and a callback function to call on the result. This could easily be expanded so that error handling can be caught and handled by another callback function but for this we’ll keep it simple.

With the view model set, the data service contract defined and being called in the function the view model is clean and not cluttered. At this point we can take a look at the data service “interface”.

Client side data service

var MyApp = MyApp || {};
MyApp.Customer = {};
MyApp.Customer.getCustomer = function (custId, callback) { };

The data service is built up with JavaScript object notation. The first two lines is to make sure that firstly there is a “MyApp” defined and it has a “Customer” property. Then the getCustomer function is defined with the set parameters required for execution and the delegate for the callback. Doing it this way you also add it into your own applications namespace and avoid cluttering up the global name space.

Lets look at the implementations for unit testing and for the actual application implementation.

The Unit Test

The test we are trying to pass is relatively simple and still based on Peter’s from the original series.

test("Get Customer",
    function () {
        stop();
        cust = new Customer();
        cust.getCustomer("ALFKI");
        setTimeout(function () {
            equals(cust.CustId(), "ALFKI", "ID not correct");
            equals(cust.CompanyName(), "My Company", "Company not correct");
            equals(cust.City(), "Reading", "City not correct");
            start();
        },
    3000);
    })

All it is trying to do is call getCustomer and make sure the data returned is bound to the correct properties.

Data service in testing

For testing purposes the view model test requires a populated JSON object to be returned from the data service. To enable the test to pass and remove the reliance on the server side test controller I create a mock client side data service before the qunit tests are added to the page.

var MyApp = MyApp || {};
MyApp.Customer = {};
MyApp.Customer.getCustomer = function (custId, callback) {
callback({ CustomerID: custId, CompanyName: "My Company", City: "Reading" });
};

All this is doing is following the contract/interface as defined for the data service, but instead of calling into a server side action it is returning a “mock” object. At this point we have removed the need for any server side calls.

After this has been defined we can now write our unit test (as above) and test that JSON object values which are being returned are bound to the correct properties.

Application implementation

So now we’ve created a mock data service and got our unit tests passing for the view model it’s time to create the actual implementation to allow for server communication and getting actual data.

var MyApp = MyApp || {};
MyApp.Customer = {};
MyApp.Customer.getCustomer = function (custId, callback) {
    var url = "@Url.Action("CustomerById", "Home")/" + custId;
    $.getJSON(url, null, callback);
};

As you can see we follow the same pattern as before but the difference is the getCustomer body implementation. We can now call into the server action and using jQuery’s $.getJSON method retrieve some json data from a server. The callback function is passed into the $.getJSON method which will delegate what needs to be done when the data is returned.

Conclusion

So to conclude client side unit tests do not need to have reliance on server side actions to execute even if they require data to be returned from an action. Some people may argue that the unit test isn’t testing the responses back from the server and handling them correctly. To do this you could go down the test controller route and get the server side to through actual errors or you could get the mock call to throw the errors.

If you have any comments about the above please post them below or contact me on Twitter - @WestDiscGolf.

No comments: