vendredi 22 juillet 2016

How to test Controller that calls a service where service uses $http

I am trying to test a controller. The controller uses a service which is using $http to get the data from a json file (This json file is just a mock up of response returned from server)

My problem is that when I am testing the controller, it creates the controller object and even calls the service. But it doesnt call the $http mocked response. I not sure where I am going wrong. I tried looking at few examples but all of them are using $q.

My service looks like this:

(function(){
  angular.module('mymodule')
    .factory('MyService', MyService);
  MyService.$inject = ['$http'];

  function MyService($http) {

    var service = {
      retrieveData : retrieveData
    };
    return service;

    function retrieveData(containerLabel){
      var myGrossData = [];
      var isMatchFound = false;
      var myindex = containerLabel.slice(-4);

      return $http.get('app/myGrossData.json').then(function(response) {
          console.log('inside http retrieveData: ');
          myGrossData = response.data;
          var myindexExists = false;

          var mydataObject = [];
          var defaultdata = [];
          angular.forEach(myGrossData, function (myGrossData) {
            if (myindex === myGrossData.myindex) {
              mydataObject = myGrossData;
              isMatchFound = true;
            }

            if(!isMatchFound && myGrossData.myindex === '2006')
            {
              mydataObject = myGrossData;
            }

            if(myGrossData.myindex === '2006'){
              defaultdata = myGrossData;
            }
          });
          if (isMatchFound && response.status === 200)
          {
            return mydataObject;
          }

          else if(!isMatchFound && (response.status === 200 || response.status === 201)){
            return defaultdata;
          }

          else //all other responses for success block
          {
            return 'Incorrect Response status: '+response.status;
          }
        },
        function(error){
          return 'Error Response: '+error.status;
        }
      );
    }   
  };
})();

The controller calling it is :

(function () {
  'use strict';
  angular
    .module('mymodule', [])
    .controller('MyCtrl', MyCtrl);

  MyCtrl.$inject = ['$scope', 'MyService'];

  function MyCtrl($scope, MyService) {
    var vm = this;
    vm.datafromsomewhere = datafromsomewhere;
    vm.displayData = [];
    vm.disableBarCode = false;
    vm.childCount = 0;
    vm.headertext="Master Container Builder";

    init();

    function init() {
      console.log('MyCtrl has been initialized!');
      console.log(vm.headertext);
    }

    function myfunctionCalledByUI(input) {
      processData(input);
    }

    function processData(containerLabel){      
      MyService.retrieveMasterContainer(containerLabel).then(function(data){
        vm.displayData = data;
      });

      vm.disableBarCode = true;
      vm.childCount = (vm.displayData.childData === undefined) ? 0: vm.displayData.childData.length;
      vm.headertext="Myindex "+vm.displayData.myindex;

      if ( vm.displayData.masterDataId.match(/[a-z]/i)) {
        // Validation passed
        vm.displayData.masterDataId ="No Shipping Label Assigned";
      }
      else
        console.log('else: '+vm.displayData.masterDataId);
      console.log('length of childData: '+vm.childCount);
    }
  }
})();

and finally my spec looks like this:

var expect = chai.expect;

describe('Test Controller', function () {

  var rootScope, compile; MyService = {};
  var $scope, $controller;
  beforeEach(module('ui.router'));

  beforeEach(function() {
    module('mymodule');

    inject(function ($rootScope, _$compile_,_$controller_) {
      rootScope = $rootScope;
      compile = _$compile_;
      $scope = $rootScope.$new();

      MyService = jasmine.createSpyObj('MyService', [
        'retrieveData'
      ]);
      $controller = _$controller_('MyCtrl', {
        $scope: $scope
      });
    });

  });




  it('controller should be initialized and data should also be initialized', function() {

    expect($controller).to.not.be.undefined;
    expect($controller).to.not.be.null;
    expect($controller.disableBarCode).to.equal(false);
    expect($controller.childCount).to.equal(0);
    expect($controller.headertext).to.equal("Master Container Builder");
  });

  it(' should process data when containerLabel is called into myfunction', function() {

    $controller.handKeyed('12001');
    expect(MyService.retrieveData).to.have.been.called;
    expect($controller.processData).to.have.been.called;
    expect($controller.disableBarCode).to.equal(true);
    expect($controller.childCount).to.equal(0);
    expect($controller.headertext).to.equal("Master Container Builder");

  });
});

I am using following techstack if it helps:

  1. angular 1.5
  2. Ionic
  3. Karma-jasmine

The code works when I run it. My issue is that when i run the test it doesnt populate the data in my vm.displayData variable. how do I make it get some data into the service. I added in some log statements and it skips it completely.

After all the test run including unrelated tests to this one, then I see the log statements from MyService. I am not sure how to approach this.

Aucun commentaire:

Enregistrer un commentaire