【问题标题】:Testing javascript function within angular scope using jasmine使用茉莉花在角度范围内测试javascript函数
【发布时间】:2014-11-17 08:00:43
【问题描述】:
我已经在 angularjs 中创建了一个应用程序,我已经学会了为 angularjs 编写 jasmine 单元测试用例,但问题是在我的应用程序中,当我为该功能我得到以下异常
ReferenceError: isInvalid is not defined
at null.<anonymous> (http://fiddle.jshell.net/_display/:83:16)
at jasmine.Block.execute (http://jasmine.github.io/1.3/lib/jasmine.js:1064:17)
at jasmine.Queue.next_ (http://jasmine.github.io/1.3/lib/jasmine.js:2096:31)
at jasmine.Queue.start (http://jasmine.github.io/1.3/lib/jasmine.js:2049:8)
at jasmine.Spec.execute (http://jasmine.github.io/1.3/lib/jasmine.js:2376:14)
at jasmine.Queue.next_ (http://jasmine.github.io/1.3/lib/jasmine.js:2096:31)
at onComplete (http://jasmine.github.io/1.3/lib/jasmine.js:2092:18)
at jasmine.Spec.finish (http://jasmine.github.io/1.3/lib/jasmine.js:2350:5)
at null.onComplete (http://jasmine.github.io/1.3/lib/jasmine.js:2377:10)
at jasmine.Queue.next_ (http://jasmine.github.io/1.3/lib/jasmine.js:2106:14)
Working Demo
【问题讨论】:
标签:
javascript
angularjs
jasmine
【解决方案1】:
angular.module('myApp',[]).controller("Controller", function($scope) {
$scope.addNumbers = function(val1, val2) {
var result = isInvalid(val1) + isInvalid(val2),
tax = 6,
watt = 5;
return (result + tax + watt);
};
});
function isInvalid(value) {
if( value=== null || value === undefined || value === '' ||isNaN(parseInt(value)))
{
return 0;
}
else
{
return value;
}
}
describe('Testing a controller', function() {
beforeEach(module("myApp"));
var ctrl, scope;
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
ctrl = $controller("Controller", {
$scope: scope
});
}));
it('test add numbers', function() {
expect(scope.addNumbers(2,6)).toMatch(19);
});
it('test isInvalid', function() {
expect(isInvalid(6)).toMatch(6);
});
});
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var trivialReporter = new jasmine.TrivialReporter();
jasmineEnv.addReporter(trivialReporter);
jasmineEnv.specFilter = function(spec) {
return trivialReporter.specFilter(spec);
};
$(function() {
jasmineEnv.execute();
});
})();
【解决方案2】:
isInvalid 在 Controller 函数的范围内定义。要对其进行测试,您应该定义控制器范围之外的函数(公共)或将其注册到 $scope 对象中。 jasmine 基本上是看不到控制器内部的。