I need to refactor the whole javascript codebase of the wordpress plugin i’m working on so that i can run unit test on it and i was looking for a place to start. I understand that i need to start using a MVC framework to do unit testing properly and i wanted a little “kick-start”. Suppose i have a very basic jQuery AJAX call, how would you write the same code in a MVC framework so that it’s unit testable?
// Refreshes the multiselect with data from facebook.
$( '.ai1ec-facebook-refresh-multiselect' ).click( function( e ) {
e.preventDefault();
// Find the spinner and show it
$( this ).closest( '.ai1ec-facebook-multiselect-title-wrapper' )
.find( '.ajax-loading' )
.css( 'visibility', 'visible' );
var type = $( this ).closest( '.ai1ec-facebook-multiselect-container' ).data( 'type' );
var that = this;
var data = {
"action" : 'ai1ec_refresh_facebook_objects',
"ai1ec_type" : type
}
$.post(
ajaxurl,
data,
function( response ) {
$( that ).closest( '.ai1ec-facebook-multiselect-title-wrapper' )
.find( '.ajax-loading' )
.css( 'visibility', 'hidden' );
if ( response.errors === true ) {
var alert = AI1EC_UTILS.make_alert( response.error_messages.join( '<br/>'), 'error' );
$( '#alerts' ).append( $alert );
return;
}
$( ' .ai1ec-facebook-multiselect-container[data-type=' + type + '] .ai1ec-facebook-multiselect ').replaceWith( response.html );
var $ok_alert = AI1EC_UTILS.make_alert( response.message, 'success' );
$( '#alerts' ).append( $ok_alert );
},
'json'
);
} );
Any javascript MVC example would be perfect.
There is not any association between using a MVC framework and having a testable code.
Neither there is a reason for thinking a non MVC framework based code can not be very testable.
It is completely possible to move all this code into a MVC implementation and having a result as tedious to test as this one.
The problem I’m seeing in the example code you showed to us is that it lacks in modularity. I’m not very pattern religious but maybe we can talk about Single responsibility here.
What I recommend here is to create isolated methods for all the logic there, organize them, put them into a Class or Utils module, then you will see how easy is to test them, in insolation and in collaboration.
Once you achieve this you can move to a MVC or not, but only because the testability of the code it is not a reason.