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');
});
});
非常感謝! – user3509516
關於測試私有函數,請參閱Philip Walton的[文章](http://philipwalton.com/articles/how-to-unit-test-private-functions-in-javascript/)。 恕我直言,這是非常周到的方法,我更喜歡在測試AngularJS代碼時使用它。 – Egel