Saturday, February 11, 2017

Testing Resolves in Jasmine

I've come across this issue before and I came up with a different answer (I think), but I can't remember that answer and I can't find it here.  So today I'm posting my new answer so at least I have this one for next time.

I'm using Angular UI Bootstrap's modal control to... open a modal.  I suppose that's kind of obvious.  Anyway, when you open a modal you can pass functions in that get resolved in the controller.  I'm not going to explain that in great detail here.

My problem was testing those resolves in my modal instance controller.  The resolves look something like this:
resolve: {
    student: function() {
        return {};
    },
    title: function() {
        return 'Add a Student';
    }
}

Since they're functions, UI Bootstrap is going to handle resolving them (get it?) to their returned values.  So when the controller loads, student will be an empty object and title will be that text.  When I test the modal instance controller I'll just be sure to inject those resolved values instead of functions.  It looks like this:
beforeEach(inject(function(_$rootScope_, _$controller_) {
    scope = _$rootScope_.$new();

    _$controller_('studentController', { $scope: scope, title: 'Add a Student', meal: {} });
}));

Now in my tests I can use those values the same way they'll be used in the actual code.  I answered a question on Stack Overflow about this topic a while back, but I can't recall what code I was looking at that prompted me to go looking for an answer that lead me to that question that I was able to answer.  Anyway, here's my answer on SO: http://stackoverflow.com/questions/37023953/unit-testing-ui-router-with-resolve/37075491#37075491