Angularjs + Jquery Draggables testing issue with Karma and Jasmine

I have an angular app that needs a small bit of jquery for complex ui drag and drop operations. To do so I am using jQuery ui draggables.

They work fine, but then I don't know very well how to apply karma/jasmine unit testing to the controllers anymore.

All my other controllers are tested without a problem but this particular controller that has jQuery now inside is the one is giving me problems.

I am receiving this karma error:

INFO [karma]: Karma v0.10.9 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Mac OS X)]: Connected on socket c8iF8rN90zbXSoEYRJzC
PhantomJS 1.9.7 (Mac OS X) ERROR
ReferenceError: Can't find variable: $

I heard that it is better to move the jQuery bits to directives. Could you please guide me in this case?

I am creating tabs in this way inside of my controller. Currently the UI works well, but as I said, it is not testable.

$scope.addSortables = function (){
    //ordering locations
    $(".dummy-widget .days-container .locations").sortable({
        "stop" : function (ui, event){

            refreshLocations(ui, event);

            PreviewManager.enableTabs();
        }
    });
}

Thanks a lot

Answers


Angular uses jqLite instead of jQuery, but it will happily use jQuery provided that you load it before you load angular. Once you do this you won't need to rely on the global $, angular.element will become your jQuery handle.

So, did you remember to load jQuery in your Karma config? It should look something like the following:

    // in karma config
    files: [
        'vendor/jquery/dist/jquery.js',
        'vendor/angular/**/*.js',
        'src/app/**/*.js',
        'spec/**/*.spec.js'
    ],

Another thing is that you should try to avoid doing direct DOM manipulation in your controller; use a directive instead. There's a good tutorial on writing angular directives here.

Hope this helps.


Need Your Help

Eclipse, Maven, AndroidAnnotations: MainActivity_ is generated but not included in apk

android eclipse maven android-annotations

I know that there are a few questions here on SO that are quite similar to mine but still none of the answers there could really help me.

Use SQLMetal on SQL Azure Database

azure sqlmetal

For reasons that I would not like to discuss, our master database schema is currently only in SQL Azure. We are working on bringing it down locally using a tool like Enzo Backup (we're waiting on ...