将Jasmine与AngularJS

时间:2015-07-28 10:51:46

标签: angularjs unit-testing karma-jasmine

我一直在关注这个开发人员的例子,了解如何使用AngularJS设置一些基本的Jasmine测试here

我的问题似乎是在整个应用程序中,我使用的是一个模块,我将其称为myApp。然而,在我的测试中,它抱怨缺少参考文献。

app.js

(function () {
    "use strict";

    var myAppModule = angular.module('myApp', ['ngAnimate', 'ngRoute', 'ui.router', 'ngResource']);
})();

dogService,JS

(function () {
        "use strict";

        var myAppModule = angular.module('myApp');
        myAppModule.factory('Dog', function () {

        var dogs = [
            { type: "Labrador", name: "Rover" },
            { type: "Tibetan Terrier", name: "Joey" },
            { type: "Yorkshire Terrier", name: "Rufus" }
        ];

        return {
            query: function () {
                return dogs;
            },
            add: function (dog) {
                dogs.push(dog);
            }
        };
    });
}());

serviceSpec.js

///<reference path="~/Scripts/jasmine.js"/>
///<reference path="~/Scripts/jasmine-html.js"/>
///<reference path="~/Scripts/boot.js"/>
///<reference path="~/Scripts/angular.js"/>
///<reference path="~/Scripts/angular-mocks.js"/>
///<reference path="~/Scripts/App/app.js"/>
///<reference path="~/Scripts/App/Services/dogService.js"/>
"use strict";
describe("dogService", function () {

    beforeEach(module("myApp"));

    describe("Dog service", function () {

        var dog;

        beforeEach(inject(function ($injector) {
            dog = $injector.get('Dog');
        }));

        it('should return 3 dogs when querying', function () {
            expect(dog.query().length).toBe(3);
        });

        it('should return 4 dogs when querying after adding a dog', function () {
            dog.add({ name: 'Fido', type: 'German Shepherd' });
            expect(dog.query().length).toBe(4);
        });
    });
});

最后我的错误:

finished in 0.071s2 specs, 2 failuresSpec List | FailuresSpec List | Failures 

dogService Dog service should return 3 dogs when querying

Error: [$injector:modulerr] Failed to instantiate module myApp due to: Error: [$injector:modulerr] Failed to instantiate module ngAnimate due to: Error: [$injector:nomod] Module 'ngAnimate' is not available! You either misspelled the module name or forgot to load it.

如果我将app.js更改为此,我将不会收到任何错误,但是我将不得不在模块的顶层注入依赖项。

(function () {
        "use strict";

        var myAppModule = angular.module('myApp', []);
    })();

有人有任何建议吗?

1 个答案:

答案 0 :(得分:0)

缺少注入myApp的角度文件的引用。

///<reference path="~/Scripts/angular-animate.js"/>
///<reference path="~/Scripts/angular-route.js"/>
///<reference path="~/Scripts/angular-ui-router.js"/>
///<reference path="~/Scripts/angular-resource.js"/>

添加这些修复它但它只是一个解决方法,因为它为每个测试脚本添加了很多引用。