2014-09-18 90 views
11

我在角度應用中使用「控制器」語法。現在是時候進行測試了,但所有的例子都是用$ scope注入的控制器。我如何調用「this.addItem」方法並檢查它是否在Jasmine測試中將項目添加到「this.items」中?用茉莉花測試角度「控制器爲」

(function() { 
"use strict"; 
    angular.module('myModule', ['factoryModule']) 
    .controller('MyController', function (myFactory) { 
     this.items = []; 

     this.selectedItem = null; 

     this.addItem = function (itemType) { 
      var item = myFactory.create(itemType); 
      this.items.push(trigger); 
      this.selectedItem = item; 
     }; 

     this.removeItem = function (item) { 
      this.items.splice(this.items.indexOf(item), 1); 
     }; 
    }); 
})(); 
+3

在您的測試中,您可以使用'$ controller'服務創建一個控制器實例。並使用該實例並在其上調用additem。然後在你的期望檢查控制器實例上的項目屬性.. – PSL 2014-09-19 01:11:52

+0

謝謝你,你的建議真的幫助! – Denis 2014-09-19 14:43:54

回答

17

只是爲了拉@ PSL的評論爲答案,該代碼爲我工作:

describe('Controller: ExampleController', function() { 

    beforeEach(module('app')); 

    var ExampleController; 

    beforeEach(inject(function ($controller) { 
    ExampleController = $controller('ExampleController', {}); 
    })); 

    it('should define foo', function(){ 
    expect(ExampleController.foo).toBeDefined(); 
    }); 
}); 
0

將以下代碼複製的文件,然後運行在瀏覽器中的文件

<html> 
    <head> 
    <!-- Jasmine References --> 
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.css"> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.js"></script> 
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine-html.min.js"></script> 
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/boot.min.js"></script> 

    <!-- Angular and Angular Mock references --> 
    <script type="text/javascript" src="https://code.angularjs.org/1.4.0-rc.2/angular.min.js"></script> 
    <script type="text/javascript" src="https://code.angularjs.org/1.4.0-rc.2/angular-mocks.js"></script> 
    </head> 
    <body></body> 
    <script type="text/javascript"> 
    angular.module('calculatorApp', []).controller('CalculatorController', function CalculatorController() { 
     self = this; 
     self.sum = function() { 
      self.z = self.x + self.y; 
     }; 
    }); 

    describe('calculator: CalculatorControllerAs', function() { 

     beforeEach(module('calculatorApp')); 

     var CalculatorControllerAs; 
     beforeEach(inject(function(_$rootScope_, _$controller_){    
      var scope = _$rootScope_.$new(); 
      CalculatorControllerAs = _$controller_('CalculatorController', {$scope: scope}); 
     })); 

     describe('sum', function() { 
      it('1 + 1 should equal 2', function() {    
      CalculatorControllerAs.x = 1; 
      CalculatorControllerAs.y = 2; 
      CalculatorControllerAs.sum(); 
      expect(CalculatorControllerAs.z).toBe(3); 
      }); 

     }); 
    }); 
    </script> 
</html>