javascript - Testing AngularUI Bootstrap modal instance controller -
this of follow-on question one: angularjs ui bootstrap mocking $modal in unit test
the referenced first-class question useful answer. question left after this: how unit test modal instance controller? in referenced so, invoking controller tested, modal instance controller mocked. arguably latter should tested, has proven tricky. here's why:
i'll re-create same illustration referenced here:
.controller('modalinstancectrl', function($scope, $modalinstance, items){ $scope.items = items; $scope.selected = { item: $scope.items[0] }; $scope.ok = function () { $modalinstance.close($scope.selected.item); }; $scope.cancel = function () { $modalinstance.dismiss('cancel'); }; }); so first thought instantiate controller straight in test, other controller under test:
beforeeach(inject(function($rootscope) { scope = $rootscope.$new(); ctrl = $controller('modalinstancectrl', {$scope: scope}); }); this not work because in context, angular not have provider inject $modalinstance, since supplied ui modal.
next, turn plan b: utilize $modal.open instantiate controller. run expected:
beforeeach(inject(function($rootscope, $modal) { scope = $rootscope.$new(); modalinstance = $modal.open({ template: '<html></html>', controller: 'modalinstancectrl', scope: scope }); }); (note, template can't empty string or fail cryptically.)
the problem have no visibility scope, customary way unit test resource gathering, etc. in real code, controller calls resource service populate list of choices; effort test sets expectget satisfy service controller using, , want validate controller putting result in scope. modal creating new scope modal instance controller (using scope pass in prototype), , can't figure out how can hole of scope. modalinstance object not have window controller.
any suggestions on "right" way test this?
(n.b.: behavior of creating derivative scope modal instance controller not unexpected – it documented behavior. question of how test still valid regardless.)
i test controllers used in modal dialogs instantiating controller straight (the same way thought above).
since there there's no mocked version of $modalinstance, create mock object , pass controller.
var modalinstance = { close: function() {}, dismiss: function() {} }; var items = []; // whatever... beforeeach(inject(function($rootscope) { scope = $rootscope.$new(); ctrl = $controller('modalinstancectrl', { $scope: scope, $modalinstance: modalinstance, items: items }); })); now dependencies controller satisfied , can test controller other controller.
for example, can spyon(modalinstance, 'close') , assert controller closing dialog @ appropriate time.
javascript angularjs unit-testing angular-ui
No comments:
Post a Comment