2014-04-15 260 views
3

我使用angularJS,我知道如何测试我的$范围与卡玛 - 茉莉对象,但我有我的测试控制器文件中经常函数和变量的困难单元测试

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


}); 

回答

4

看起来你试图测试在角度控制器中声明的私有变量。没有通过$ scope公开的变量不能被测试,因为它们是隐藏的,并且仅在控制器内部的函数范围内可见。更多关于私人会员和隐藏在JavaScript中的信息,你可以找到here

你应该如何应对私人领域的测试方式是通过测试他们通过暴露的API。如果变量没有在任何暴露的公开方法中使用,则意味着它没有被使用,因此保留它并测试它是没有意义的。

+0

非常感谢! – user3509516

+3

关于测试私有函数,请参阅Philip Walton的[文章](http://philipwalton.com/articles/how-to-unit-test-private-functions-in-javascript/)。 恕我直言,这是非常周到的方法,我更喜欢在测试AngularJS代码时使用它。 – Egel