• Mocking AngularJS promise callback params in Jasmine tests

    Mocking AngularJS promise callback params in Jasmine tests

    You could argue that in a scenario such as this one, you should ideally have a separate, stand-alone callback function to handle the success response of a promise, but this post is not about that. It’s about an occasional need to mock a promise and perhaps it’s callback params in Jasmine unit-tests and this is a simple example of how it can be done.

    This is an example of a function you might find in an AngularJS controller (written in TypeScript, but doesn’t matter, it would be almost identical in JS).

    It contains a call to a service function which in turn returns a promise. That promise returns a successResponse and that’s what we’re about to mock. What we want to test is a situation where a $http request didn’t fail, but it didn’t return any data either. In that case, we might want to display a toast message and skip refreshing the local cache.

    The following Jasmine test explains the code in-line. Two crucial parts are creation of the promise and how to resolve it and forcing the angular digest cycle with $rootScope.$apply(). The $apply() is needed because we’re invoking the promise from the Jasmine side, which is sort of “from the outside” and AngularJS will not be aware of that the event occurred so we need to let it know manually (the promise resolution wasn’t triggered by AngularJS itself internally).

    Hope that helps. If you know of an easier way to do this, please let me know in the comments. Thanks!

     

  • Dynamically resolving function shared arguments in JavaScript

    Dynamically resolving function shared arguments in JavaScript

    Sometimes we have functions which expect the same arguments as other functions, all fine there. Sometimes these arguments are obtained/resolved asynchronously. If there are a lot of these functions that share the same resource, we can come up with lot of unnecessary boilerplate.

    Imagine having a function like resolveMetaData() which asynchronously obtains fresh data every time it’s called (to keep the code at a very simple level, for the purpose of this post I’ll be using setTimeout() instead of something a bit more complex like an AJAX call):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function resolveMetaData(callback) {
        // for the purpose of the demo we'll simply mock the metaData object    
        var metaData = { message: "Meta message", start: new Date() };

        // async business logic example
        setTimeout(function () {
            metaData.end = new Date();
            // after metaData is ready, resolve callback
            callback(metaData);
        }, 1000);
    }

    And two functions that require a new instance of metaData upon their execution:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    function fnOne(data, metaData) {
        console.log(data);
        console.log(metaData);
    }

    function fnTwo(id, data, metaData) {
        console.log(id);
        console.log(data);
        console.log(metaData);
    }

    The simplest way to provide the latest metaData to these functions would be to use callbacks like this:

    1
    2
    3
    4
    5
    6
    7
    resolveMetaData(function(metaData) {
        fnOne("fnOne", metaData);
    });

    resolveMetaData(function(metaData) {
        fnOne(1, "fnTwo", metaData);
    });

    If you had to write a lot of functions similar to fnOne() and fnTwo() (ie. 10 or more) and all of them required the latest metaData, you would most probably be tempted to somehow reduce the code and get rid of the callback boilerplate. The first two ideas that came to my mind on how to resolve this were function overloads and/or having a base function that would handle metaData resolving. Since JS doesn’t really support overloading (in the same way as say C# does), having a base function to handle metaData resolving seems like a safe bet. The only question is – how do we call a function in JS with the parameters we got and resolve the shared parameters asynchronously?

    Fortunately Function.prototype.apply() comes to the rescue! It allows us to call a function with arguments as an array which is quite handy. Since functions in JS are objects, we can now create a base function which accepts the function object of the function we wish to call, and the args we have at that point. It then resolves metaData, appends it to the arguments array and calls the passed function with these arguments. This is how the base function would look like:

    1
    2
    3
    4
    5
    6
    function fnBase(fn, args) {
        resolveMetaData(function (metaData) {
            args.push(metaData);
            fn.apply(this, args);
        });
    }

    And this is the how we can now call fnOne() and fnTwo() through the fnBase():

    1
    2
    fnBase(fnOne, ["fnOne"]);
    fnBase(fnTwo, [1, "fnTwo"]);

    It would be possible to place metaData as a first argument in fnOne() and fnTwo() signatures but that would require additional args position handling in fnBase() so it is probably best to put metaData as the last argument.

    That’s it, hope it helps. Enjoy! :)

  • Returning value from fragment into parent activity on Android

    Returning value from fragment into parent activity on Android

    This post will show you how to return a value set in a dialog fragment back to the parent activity it was called from. Code sample provided here is from the Auto-WOL app I made not so long ago, so if you need the bigger picture, feel free to check TimePickerFragment and DeviceActivity classes over at github. This example uses TimePickerDialog. It also keeps track of the layoutId (where the layout it is bound to acts as a button in the UI) because in my app I have multiple buttons which can invoke the same TimePickerFragment so I needed to know which button invoked the dialog fragment because upon selecting the time the button caption gets updated.

    auto-wol-fragment-activity

    So, to make this whole thing work, we will need a fragment class which will extend DialogFragment and implement TimePickerDialog.OnTimeSetListener. This class will expose the OnTimePickedListener interface so it could later be consumed by the parent activity. This class will also be responsible for registering and calling the callback on time set event. The defined OnTimePickedListener interface has only one method signature – onTimePicked(), which will need to be implemented by the parent activity. Other than this, the class only has a few more overrides and that’s all.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    /**
     * This class is used so values from TimePickerFragment could be
     * returned back to the activity from which it was called.
     */

    public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
        OnTimePickedListener mCallback;
        Integer mLayoutId = null;

        /**
         * An interface containing onTimePicked() method signature.
         * Container Activity must implement this interface.
         */

        public interface OnTimePickedListener {
            public void onTimePicked(int textId, int hour, int minute);
        }

        /* (non-Javadoc)
         * @see android.app.DialogFragment#onAttach(android.app.Activity)
         */

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);

            try {
                mCallback = (OnTimePickedListener)activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString() + " must implement OnTimePickedListener.");
            }
        }

        /* (non-Javadoc)
         * @see android.app.DialogFragment#onCreateDialog(android.os.Bundle)
         */

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            mCallback = (OnTimePickedListener)getActivity();

            Bundle bundle = this.getArguments();
            mLayoutId = bundle.getInt("layoutId");
            int hour = bundle.getInt("hour");
            int minute = bundle.getInt("minute");

            // Create a new instance of TimePickerDialog and return it
            return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
        }

        /* (non-Javadoc)
         * @see android.app.TimePickerDialog.OnTimeSetListener#onTimeSet(android.widget.TimePicker, int, int)
         */

        public void onTimeSet(TimePicker view, int hour, int minute) {
            if(mCallback != null)
            {
                mCallback.onTimePicked(mLayoutId, hour, minute);
            }
        }
    }

    The parent activity class implements the OnTimePickedListener defined in TimePickerFragment. This means we are requried to override the onTimePicked() method. This method is what gets executed after time has been picked in the dialog pop-up and “Done” confirmation button has been pressed. From here you’re back in your activity class and can do whatever you want with the obtained data.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    public class DeviceActivity extends BaseActivity implements OnTimePickedListener {    
        ...
       
        /**
         * On time picked event, converts hour and minutes values to milliseconds
         * milliseconds and sets a new value for the layout in the activity.
         * @param layoutId      QuietHoursFrom or QuietHoursTo layout Id.
         * @param hour          Hour value.
         * @param minute        Minutes value.
         */

        @Override
        public void onTimePicked(int layoutId, int hour, int minute) {
            Long timeInMillis = TimeUtil.getTimeInMilliseconds(hour, minute);
           
            // Here you can do whatever needed with value obtained from the fragment
        }
       
        ...
    }
Back to top