Angularjs / Karma:未捕获的ReferenceError:未定义注入

时间:2016-06-25 10:41:20

标签: angularjs jasmine karma-runner

我得到了这项服务

angular.module('common.utils', [])

.service('Timer', function () {
    function Timer() {
        var start = new Date();
        return function () {
           return (new Date()).getTime() - start.getTime();
        };
    }
    return Timer;
});

我正在尝试为它编写一个简单的测试:

describe('common.utils', function() {

    beforeEach(function () {
        module('common.utils');
    });

    it('has a timer service', inject(function(Timer) {
        expect(Timer).not.toBeNull();
    }));

}); 

我一直在ReferenceError: inject is not defined

我添加了angular.jsangular-mocks.js以及所有应用文件(module正在运行...)。我不明白问题是什么......

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。

事实证明问题出在文件的加载顺序上。您必须在加载jasmine之前加载angular-mocks

以下加载顺序将抛出问题中提到的错误:

<script src="/bower_components/angular/angular.js"></script>
<script src="/bower_components/angular-mocks/angular-mocks.js"></script>
<script src="/bower_components/jasmine/lib/jasmine-core/jasmine.js"></script>
<script src="/bower_components/jasmine/lib/jasmine-core/jasmine-html.js"></script>
<script src="/bower_components/jasmine/lib/jasmine-core/boot.js"></script>

<!-- include spec files here... -->
<script src="/spec/test.js"></script>
  

ReferenceError:未定义注入

在几个茉莉花例子中,代码中还包含一个附加注释:

<!-- include source files here... -->

评论有助于我们提醒您按正确的顺序加载内容。

<script src="/bower_components/jasmine/lib/jasmine-core/jasmine.js"></script>
<script src="/bower_components/jasmine/lib/jasmine-core/jasmine-html.js"></script>
<script src="/bower_components/jasmine/lib/jasmine-core/boot.js"></script>

<!-- include source files here... -->
<script src="/bower_components/angular/angular.js"></script>
<script src="/bower_components/angular-mocks/angular-mocks.js"></script>

<!-- include spec files here... -->
<script src="/spec/test.js"></script>