【问题标题】:How to test an angular app with class inheritance?如何测试具有类继承的角度应用程序?
【发布时间】:2014-06-04 19:29:37
【问题描述】:

我可以很好地测试普通控制器。我无法测试继承基本控制器的控制器。

这就是我们定义子类控制器的方式:

 app.NavController = app.BaseController.extend({
    ...
 });

这是基地:

app.BaseController = Class.extend({
    $scope: null,

    init: function($scope) {
        this.$scope = $scope;
        this.defineListeners();
        this.defineScope();
    },

    defineListeners: function() {
        // this.$scope.$on('$destroy',this.destroy.bind(this));
    },
    ...
});

app.controller('BaseController', ['$scope', function($scope) {
    return new app.BaseController($scope);
}]);

但是,运行 Karma 会产生:

TypeError: 'undefined' is not an object (evaluating 'app.BaseController.extend')

有没有其他方法可以做到这一点?我已经删除了 IIFE 包装器进行测试。 Class.js 包含在我的 Karmaconfig 中。我正在使用 John Resig 的类继承。

【问题讨论】:

  • 我的队友可能在 app 上定义了 BaseController,因为他正在做 IIFE 包装器。也许这不是必需的?我们可以将 BaseController 定义为全局吗?
  • 你能提供一些你的测试代码吗?
  • 这失败了,因为它只是包含在 Karma 的页面上。我相信这发生在规范运行之前。我们实际上想出了一个使用 $controller 并覆盖原型的解决方案。

标签: angularjs unit-testing inheritance testing karma-runner


【解决方案1】:

通过添加它来实例化子类原型,我们可以通过简单地将 $controller 作为依赖项注入来访问基类。

app.controller('SubController', ['$scope','$location','$controller',
        function($scope, $location, $controller) {
            var controller = {

...
controller.prototype = $controller('BaseController', {
                $scope: $scope
            });
            controller.init($location);
return controller;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2015-11-05
    • 2011-09-10
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多