用茉莉花测试角度“控制器”

时间:2014-09-18 21:58:52

标签: angularjs testing jasmine bdd

我在角应用中使用“控制器为”语法。现在是测试的时候了,但所有的例子都是注入$ 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);
        };
    });
})();

2 个答案:

答案 0 :(得分: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();
  });
});

答案 1 :(得分: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>