Search code examples
jqueryajaxunit-testingdatatablesintern

jQuery Datatable - unit testing logic residing event callback


I am writing some unit test against a datatable rendered on a view and able to test datatable rendering successfully. That mean table is rendering based ajax response. But when I trying to test some logic written inside the event callback (such as draw, xhr), it seems none of the events are getting fired.

var table = this.ui.table.DataTable(dataTablesOptions)
.on('xhr', function($event, dataTableSettings, jsonResponse, xhr) {
  //some logic inside
}}.on('draw', function ($event, dataTableSettings){
  //logic
});

Everything is working correctly in application, only occurring at writing unit test.

Have anyone experienced similar issue?

Thanks Peter


Solution

  • When writing a test for asynchronous logic (like XHR), make sure to either return a Promise or declare the test explicitly async with this.async() (and then resolve the Deferred object that gives you). You should end up with something like:

    myTest: function () {
        var dfd = this.async();
    
        var table = this.ui.table.DataTable(dataTablesOptions)
            .on('xhr', function($event, dataTableSettings, jsonResponse, xhr) {
                //some logic inside
                dfd.resolve();
            }).on('draw', function ($event, dataTableSettings){
                //logic
                dfd.resolve();
            });
    }
    

    How you actually resolve the Deferred depends on your test logic. For example, if two events should happen, you could call this.async(5000, 2), which would set the test timeout to 5000ms, and tell Intern to wait for the Deferred to be resolved twice before considering the test finished. There are also some convenience methods attached to the Deferred, like callback and rejectOnError, that can simplify its usage somewhat.