【问题标题】:How do I represent my controller in a Jasmine/Karma test如何在 Jasmine/Karma 测试中代表我的控制器
【发布时间】:2015-10-02 17:35:48
【问题描述】:

我正在尝试使用 Jasmine 和 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

【问题讨论】:

  • 我看到的东西非常相似。就我而言,部分原因是inject() 抛出异常(在调用回调之前)“模块'angulartics'不可用!您拼错了模块名称或忘记加载它。如果注册模块确保您将依赖项指定为第二个参数。”我以与您传递 ngCookies 相同的方式传递 angularitics。而且我确定我已经包含它,只是可能在错误的地方?希望这里提出的任何解决方案也可以帮助我!

标签: angularjs jasmine karma-jasmine


【解决方案1】:

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

所以我修复了这个问题,然后得到了与您相同的“参数 'fn' 不起作用”错误消息。

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

然后我将 beforeEach() 代码更改为:

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

module('Sheets');

现在我传递给注入的回调确实被调用了。

假设您可以尝试更改:

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

beforeEach(module("myApp"));

...看看会不会更进一步。

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

【讨论】:

  • 是的,这确实让我解决了范围问题。这看起来像是 Angular 文档中的一个错误!谢谢。现在我必须弄清楚如何将所有这些东西注入控制器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-24
  • 2014-05-01
  • 1970-01-01
  • 2015-01-23
  • 2016-09-13
  • 2019-02-17
  • 2017-06-03
相关资源
最近更新 更多