加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

单元测试 – AngularJS:Mock对象通过路由器的解析注入控制器

发布时间:2020-12-17 07:19:24 所属栏目:安全 来源:网络整理
导读:我正在尝试通过路由器的解决方案测试接收对象的控制器: app.js: ....when('/confirm',{ templateUrl: 'views/confirm.html',controller: 'ConfirmCtrl',resolve: { order: function(Order) { return Order.current; } }})... ConfirmCtrl.js: angular.mod
我正在尝试通过路由器的解决方案测试接收对象的控制器:

app.js:

...
.when('/confirm',{
  templateUrl: 'views/confirm.html',controller: 'ConfirmCtrl',resolve: {
    order: function(Order) {
      return Order.current;
    }
  }
})
...

ConfirmCtrl.js:

angular.module('angularGeolocationApp').controller('ConfirmCtrl',function($scope,order,...) {

  $scope.order = order

  ...

});

我的测试看起来像这样:

'use strict';

describe('Controller: ConfirmCtrl',function () {

  // load the controller's module
  beforeEach(module('angularGeolocationApp'));

  var ConfirmCtrl,scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller,$rootScope) {
    scope = $rootScope.$new();
    ConfirmCtrl = $controller('ConfirmCtrl',{
      $scope: scope
    });
  }));

  it('should get an order object',function () {
    expect(_.isObject(scope.order)).toBeTruthy();
  });

  ...
});

然而,第一次期望失败:

PhantomJS 1.9.2 (Mac OS X) Controller: ConfirmCtrl should get an order object FAILED
    TypeError: Attempted to assign to readonly property.
        at workFn (/Users/jviotti/Projects/Temporal/angular/angular-geolocation/app/bower_components/angular-mocks/angular-mocks.js:2107)
    Expected false to be truthy.

我的假设是,当我对隔离控制器进行单元测试时,路由器没有更改来运行resolve函数并分配正确的值.

有没有办法模拟订单依赖?

我知道我可以摆脱解决方案并在控制器本身中注入Order并将$scope.order实例化为Order.current,但我想保留解决方法.

只需将自己的顺序放入ctrl的构造函数中,就像这样.
describe('Controller: ConfirmCtrl',scope,order


  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller,$rootScope) {
    order = {};
    scope = $rootScope.$new();
    ConfirmCtrl = $controller('ConfirmCtrl',{
      $scope: scope,order: order
    });
  }));

  it('should get an order object',function () {
    expect(_.isObject(scope.order)).toBeTruthy();
  });

  ...
});

问候

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读