【问题标题】:How to Mock $location.path in Angular Unit Test (Mocha)如何在 Angular 单元测试 (Mocha) 中模拟 $location.path
【发布时间】:2015-11-23 19:02:25
【问题描述】:

我正在使用 Karma、Mocha、Sinon 和 Chai 进行 Angular 单元测试,我正在尝试弄清楚如何使用 $location 在控制器中模拟重定向。

我的控制器执行以下重定向:

$location.path('home');

我想尝试使用间谍来模拟重定向,这就是我目前正在做的事情:

describe('Auth Controller', function() {
  var controller;
  var $location;

  beforeEach(function() {
    bard.appModule('app.auth');
    bard.inject('$controller', '$rootScope', '$location');
  });

  beforeEach(function() {
    $location = {
      path: sinon.spy().returned('Fake location')
    };
    controller = $controller('authCtrl', { $scope: $rootScope, $location: $location });
  });

  it('should take you to the metrics page on successful login', function() {
    expect($location.path).to.have.been.calledWith("Fake location");
  });

});

我收到以下错误:

TypeError: false is not a spy or call to a spy!

我不确定如何正确地模拟这个,或者我什至是否以正确的方式处理这个。

感谢单元测试专家的任何帮助。提前致谢!

【问题讨论】:

  • 为什么需要模拟 $location?通常我不会嘲笑它,我只是像这样使用 expect(location.path()).toBe('/myPage');
  • 你这样做有什么特别的原因吗?我认为这个想法是模拟 $location 服务。
  • 没有什么特别的原因,对我来说这是测试重定向行为的最简单方法
  • @RafaelZeffa 所以我正在尝试这个:expect($location.path()).to.equal('login'); 但我收到了这个错误:TypeError: Cannot read property 'path' of undefined

标签: angularjs unit-testing sinon chai karma-mocha


【解决方案1】:

您可以像这样使用 Spies 来测试 location.path(参见此处:Spy on a service method call using jasmine Spies):

var location, objectUnderTest;

beforeEach(inject(function($location){
  location = $location;
}));
function YourCtrlMaker() {
    objectUnderTest = $controller('YourCtrl', {
        $scope: $scope,
        $location: location,
        $routeParams: $routeParams,
    })
}
it('should test location.path', function(){
  spyOn(location, 'path');
  YourCtrlMaker();
  $scope.$root.$digest();
  expect(location.path).toHaveBeenCalledWith('example.com/objects/');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-30
    • 2019-09-09
    • 2018-11-06
    • 1970-01-01
    • 2018-11-24
    • 2021-09-18
    • 2019-08-26
    • 2020-11-19
    相关资源
    最近更新 更多