如何在Jasmine / Karma测试中代表我的控制器

时间:2015-10-02 17:35:49

标签: angularjs jasmine karma-jasmine

我正在尝试使用Jasma和Karma来测试我的AngularJS控制器。 当我尝试documented procedure配置控制器测试时,没有创建$ scope。实际上看起来就像之前根本没有执行。

这是我的控制器声明:

angular.module("myApp", ["ngCookies"])
       .controller("myCtrl", function($scope, $window, $location, MyService, 
                   $timeout, $log, $cookies, $q) {

我的测试看起来像这样:

describe("MyController test", function() {
var $scope;

beforeEach(
    module("myApp", ["ngCookies"]));
beforeEach(inject(function($rootScope, $controller) {
    $scope = $rootScope.$new(); // It looks like this is never called
    scope =$scope;
    $controller("myCtrl", {$scope: $scope});
}));
it("Checks the state of various units", function() {

    ...
});

看起来从未调用过beforeEach的东西。我认为我需要将其余属性注入控制器,但如果是这样,我不确定如何。

这是测试运行日志中的错误

FAILED MyController test Checks myFunction starting from blank state
Error: [$injector:modulerr] Failed to instantiate module ngCookies due to:
Error: [ng:areq] Argument 'fn' is not a function, got string
http://errors.angularjs.org/1.3.14/ng/areqp0=fn&p1=not%20a%20function%2C%20got%20string

1 个答案:

答案 0 :(得分:1)

我在你的问题评论中提到的我最初的问题是我试图包含非最小化版本的angulartics.js,但是没有这样的事情。将angulartics.js改为angulartics.min.js解决了我的特殊问题。

所以我解决了这个问题,然后得到了相同的“Argument'fn'不是函数”错误消息。

我意识到我们的代码都是在调用module()时创建一个新模块,而不是检索现有的(“myApp”)模块,这与示例代码不同。

然后我改变了我的beforeEach()代码:

module('Sheets', ['ngResource', 'angulartics', 'angulartics.google.analytics']);

module('Sheets');

现在确实调用了我传递给inject的回调。

假设您可以尝试更改:

beforeEach(module("myApp", ["ngCookies"]));

beforeEach(module("myApp"));

......看看能不能再进一步了。

对我来说,这仍然只是货物编程,我不知道它为什么有用,所以在我感觉正确之前,我还有更多的学习要做。如果您(或其他任何人)可以提供检索现有模块与创建新模块相关的原因,那么肯定会为您提供答案或评论!