Nig*_*ter 1 javascript visual-studio jasmine chutzpah angularjs
我正在使用VS2013编程,并希望在我的AngularJs控制器上进行单元测试.例如,我有一个taController.js,如下所示:
var module = angular.module("MyApp", []);
var TAController = ["$scope",
function ($scope) {
$scope.myNumber = 2;
$scope.add = function (number) {
$scope.myNumber = $scope.myNumber + number;
};
}];
Run Code Online (Sandbox Code Playgroud)
一个使用它的HTML页面如下所示:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="MyApp">
<head>
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/taController.js"></script>
</head>
<body>
<div id="myDiv" data-ng-controller="TAController">
{{myNumber}}<br />
<a href="" ng-click="add(2)">Add 2</a><br />
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我想用Jasmine和Chutzpah创建一个单元测试.我在我的测试项目的specs目录中创建了一个AngularTest.js,看起来像这样
/// <reference path="../scripts/jasmine.js" />
/// <reference path="../../unittestingwithjasmine/scripts/tacontroller.js" />
describe("My Tacontroller", function () {
var element;
var myScope;
beforeEach(inject(function($scope) {
myScope = $scope;
}));
it("should be able to add 2 plus 2", function () {
myScope.add(2)
expect(myScope.myNumber).toBe(4);
});
});
Run Code Online (Sandbox Code Playgroud)
我认为上面的代码有很多错误.第一个是测试失败 - 我的Tacontrooler遇到了声明异常.消息:RefferenceError:找不到cariable:inject in file:///C....../specs/angulaertest.js(第10行)
我的问题是如何编写我的AngularTest.js以通过我的Tacontroller上的添加功能进行正确测试
注入在哪里定义?您需要让Chutzpah知道在哪里可以找到所有依赖项.建议的方法是使用chutzpah.json文件及其引用设置.你可以在这里阅读关于在Chutzpah设置参考资料的内容
chutzpah.json的一个例子如下:
{
"Framework": "jasmine",
"References" : [
{"Path" : "someReference.js" },
{"Path" : "someCode.js" }
],
"Tests" : [
{"Include": "tests/*.js"}
]
}
Run Code Online (Sandbox Code Playgroud)
错误是我需要包括角度和角度模拟.我还需要从根范围获取范围.以下代码有效
/// <reference path="../scripts/jasmine.js" />
/// <reference path="../scripts/angular.js" />
/// <reference path="../scripts/angular-mocks.js" />
/// <reference path="../../unittestingwithjasmine/scripts/tacontroller.js" />
describe("My Tacontroller", function () {
var myScope;
beforeEach(inject(function($rootScope, $httpBackend, $controller) {
myScope = $rootScope.$new();
$controller('TAController', { $scope: myScope});
}));
it("should be able to add 2 plus 2", function () {
myScope.add(2);
expect(myScope.myNumber).toBe(4);
});
});
Run Code Online (Sandbox Code Playgroud)
我已经找到了2个非常好的博客条目,证明了这一点,以及如何将它带到下一步http://odetocode.com/blogs/scott/archive/2013/06/10/simple-unit-tests-with-angularjs .aspx http://odetocode.com/blogs/scott/archive/2013/06/11/angularjs-tests-with-an-http-mock.aspx
我希望这有助于其他人......