how to mock a location.path in angular unit tests

≯℡__Kan透↙ 提交于 2019-12-01 10:39:22

问题


http://blog.artlogic.com/2013/05/06/angularjs-best-practices-ive-been-doing-it-wrong-part-2-of-3/

I am testing a routing directive with location.path refs to templates that cannot be found. So....

I want to mock a routing test with a mock configured $routeProvider, how to get the $routeProvider in karma/jasmine?

then I tried the spyOn mock approach described in best-practice, is there a syntax for which I can expect the $location.path().toBe('/path')?

spyOn($location, 'path').andCallFake(new LocationMock().path);

and I was wondering if I could


回答1:


I created a fiddle which demonstrates mocking $location.

  app.controller('testcont', function($scope, $location) {
      $scope.path = $location.path();
  });
  ...
  beforeEach(inject(function($controller, $rootScope, $location){    
     scope = $rootScope.$new();
     spyOn($location, 'path').andReturn('Fake location');
     $controller('testcont', {$scope:scope});
  }));
  ...
  it('should spy on $location', function($location){
     expect(scope.path).toBe('Fake location');
  });

However templates can be loaded by prepopulating Angular's $templateCache with the directive. Karma uses the ng-html2js-preprocessor. Could that help your problem?



来源:https://stackoverflow.com/questions/19642162/how-to-mock-a-location-path-in-angular-unit-tests

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