2014-04-15 258 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