使用Karma-Jasmine进行单元测试

时间:2014-04-15 01:04:20

标签: angularjs karma-jasmine

我正在使用angularJS,我理解如何使用karma-jasmine测试我的$ scope对象,但是我在控制器文件中测试常规函数和变量时遇到了困难

//controller.js
angular.module('myApp').controller('mainCtrl', function ($scope) {
    $scope.name = "bob";

    var aNumber = 34;

    function myFunction(string){
      return string;
    }
});

我想做的是测试是否期望(aNumber).toBe(34);

// test.js
describe('Controller: mainCtrl', function () {

  // load the controller's module
  beforeEach(module('myApp'));

  var mainCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    mainCtrl = $controller('mainCtrl', {
      $scope: scope
    });
  }));

  // understand this
  it('should expect scope.name to be bob', function(){
   expect(scope.name).toBe('bob');
  });

  // having difficulties testing this
  it('should expect aNumber to be 34', function(){
    expect(aNumber).toBe(34);
  });

  // having difficulties testing this    
  it('should to return a string', function(){
    var mystring = myFunction('this is a string');
    expect(mystring).toBe('this is a string');
  });


}); 

1 个答案:

答案 0 :(得分:4)

看起来你正试图测试在角度控制器中声明的私有变量。未通过$ scope公开的变量无法进行测试,因为它们是隐藏的,并且仅在控制器内的函数范围内可见。有关私人会员和隐藏在javascript中的信息的更多信息,您可以找到here

在测试中如何处理私有字段的方法是通过公开的api测试它们。如果变量未在任何公开的公开方法中使用,则意味着它没有被使用,因此保留并测试它是没有意义的。