我正在使用一个使用自定义指令的AngularJS应用程序。我也试图在我的应用程序中使用单元测试。所以,我正试图利用Jasmine。目前,我的单元测试是问题所在。目前,它看起来如下:
myDirective.spec.js
describe('Directive: myDirective', function () {
describe('Function: myProcedure', function () {
it('should word', function ($rootScope, $compile) {
var e = angular.element('<div><br /></div>');
console.log($compile);
$compile(e)($rootScope);
expect(true).toBe(true);
});
});
});
此测试抛出异常。运行console.log行时,它会打印:'undefined'。下一行向Jasmine抛出一个错误:'TypeError:undefined不是函数'。
就像我没有注入$ compile服务一样。但是,我相信我是这样做的。我的测试运行器如下所示:
<html ng-app="testApp">
<head>
<title></title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine-html.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/boot.js"></script>
<script type="text/javascript" src="index.html.js"></script>
<script type="text/javascript" src="directives/myDirective.js"></script>
<script type="text/javascript" src="tests/unit/myDirective.spec.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.css" />
</head>
<body>
<a href="#" onclick="env.execute()">run tests</a>
</body>
</html>
为什么我不能运行这个基本测试?我做错了什么?
答案 0 :(得分:4)
首先你必须添加角度模拟:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-mocks.js">
</script>
然后加载模块并在beforeEach
块中注入$ compile / $ rootScope:
describe('Directive: myDirective', function () {
var $compile;
var $rootScope;
beforeEach(module('testApp'));
beforeEach(inject(function(_$compile_, _$rootScope_){
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
describe('Function: myProcedure', function () {
it('should word', function () {
var e = angular.element('<div><br /></div>');
$compile(e)($rootScope);
expect(true).toBe(true);
});
});
});
检查单元测试文档:http://docs.angularjs.org/guide/dev_guide.unit-testing#directives
答案 1 :(得分:0)
jasmine提供的it()函数不会为您进行任何注入,因此您需要将角度组件注入测试中。修改您的测试,如下所示:
describe('Directive: myDirective', function () {
describe('Function: myProcedure', function () {
it('should word', function () {
inject(function ($rootScope, $compile) {
var e = angular.element('<div><br /></div>');
//rest of code goes here
});
您还需要引用angular.mocks library。
答案 2 :(得分:0)
我刚才遇到过这个问题,这就是我的日子(实际上是最终结果)。只需添加&#34;模块(&#39; ng&#39;);&#34;以及模块(&#39; yourAppModule&#39;)。它应该工作。