vendredi 29 avril 2016

Angular Testing: It's valid testing that an service not to have been called when I test a restricted submit data?

I have this code:

angular
  .module('ExampleApp')
  .service('MyService', Service);

function Service(){
  var self = this;

  self.save = function(_data){
    //save the data in the server
  } 
}


angular
  .module('ExampleApp')
  .controller('MyCtrl', Controller);

Controller.$inject = ['MyService']

function Controller(MyService){
  var vm = this;
  vm.invalidDataExist = false;
  vm.data = {};
  vm.submit = function(){
     //call a function that check if exist data invalid
     vm.invalidDataExist = checkIfExistDataInvalid();
     if(!vm.invalidDataExist){
       MyService.save(vm.data);
     }   
  }
}

My idea is generate a test that simulates that exist data invalid and ensure that the service have not been called:

describe('MyCtrl', describeSpec);

function describeSpec(){
  var MyCtrl, MyService

  beforeEach(module('ExampleApp'));
  beforeEach(inject(eachSpecSetup));

  function eachSpecSetup($controller, _MyService_){
    MyCtrl = $controller('MyCtrl');
    MyService = _MyService_;
  }

  it('Should not called a service if exist data invalid', spec1);

  function spec1(){
    spyOn(MyService, 'save');

    //I create a invalid data here

    MyCtrl.submit();

    expect(MyService.save).notHaveBeenCalled();

  }

}

My questions:

  • This is a valid testing idea?
  • What is the "standard" way to check cases how this?

Aucun commentaire:

Enregistrer un commentaire