Mocking $routeParams in a test in order to change its attributes dynamically

久未见 提交于 2019-12-04 09:44:02

The thing is, what you don't want to do, is probably the best solution you have. A mock makes sense when what you want to mock is kinda complex. Complex dependency with methods, lot of states, etc. For a simple object like $routeParams it makes all the sense of the world to just pass a dummy object to it. Yes it would require to instantiate different controllers per test, but so what?

Structure your tests in a way that makes sense, makes it readable and easy to follow.

I suggest you something like:

describe('Controller: Foo', function() {
  var $controller, $scope;

  beforeEach(function() {
    module('app');

    inject(function($rootScope, _$controller_) {
      $scope = $rootScope.$new();routeParams = {};

      $controller = _$controller_;
    });
  });

  describe('With PG_FIRST', function() {
    beforeEach(function() {
      $controller('Foo', { $scope: $scope, $routeParams: {'PG': 'PG_FIRST'}}); 
    });

    it('Should ....', function() {
      expect($scope.something).toBe('PG_FIRST');
    });
  });

  describe('With PG_SECOND', function() {
    beforeEach(function() {
      $controller('Foo', { $scope: $scope, $routeParams: {'PG': 'PG_SECOND'}}); 
    });

    it('Should ....', function() {
      expect($scope.something).toBe('PG_SECOND');
    });
  });
});

With a good test organization, I can say that I like this test easy to follow.

http://plnkr.co/edit/5Q3ykv9ZB7PuGFMfWVY5?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!