Search code examples
javascriptunit-testinglodashistanbuljasmine2.0

Testing Lodash sortBy function argument using Jasmine


I have a controller in my project that goes like this:

define(function (require) {
  'use strict';

  function AllOrgsController($rootScope, $uibModalInstance) {
    var vm = this;
    var clonedOrgs = _.cloneDeep($rootScope.userData.org);
    vm.modelContainer = _.sortBy(clonedOrgs, function (org) {
      return org.organizationName.toLowerCase();
    });

    vm.openFacilityModal = function () {
      $uibModalInstance.close();
    };

    vm.saveOrgsModal = function () {
      $uibModalInstance.close({ $value: vm.currentFacility });
    };

    vm.cancelOrgsModal = function () {
      $uibModalInstance.dismiss();
    };
  }

  AllOrgsController.$inject = ['$rootScope', '$uibModalInstance'];

  return AllOrgsController;
});

But the anonymous function being used within Lodash’s _.sortBy method is not covered according to Istanbul. Since I’m a noob with unit testing I haven’t figured out why – does anybody know?

"function not covered" error message on my code


Solution

  • _.sortBy should call the function you passed for each element of the clonedOrgs parameter you gave it. Since Istanbul detected that the passed-in function was never run, that must mean that clonedOrgs is always empty (or not a valid array) in your tests. So you can make sure that method is covered by writing a test in which your $rootScope.userData.org array contains elements.