角度测试:在测试受限制的提交数据时,是否有效测试是否未调用服务?

时间:2016-04-29 16:08:51

标签: angularjs testing jasmine spy

我有这段代码:

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);
     }   
  }
}

我的想法是生成一个模拟现有数据无效的测试,并确保未调用该服务:

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).not.toHaveBeenCalled();
  }  
}

我的问题:

  • 这是一个有效的测试理念?
  • 检查案件的“标准”方法是什么?

0 个答案:

没有答案