【问题标题】:Unit-testing with Karma-Jasmine使用 Karma-Jasmine 进行单元测试
【发布时间】:2014-04-15 01:04:20
【问题描述】:

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

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

    var aNumber = 34;

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

我想做的是测试看看是否expect(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');
  });


}); 

【问题讨论】:

    标签: angularjs karma-jasmine


    【解决方案1】:

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

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

    【讨论】:

    • 查看 Philip Walton 的 article 关于测试私有函数的内容。恕我直言,这是一种非常周到的方法,我更喜欢在测试 AngularJS 代码时使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2015-11-12
    • 2017-01-03
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多