How to unit test angularjs controller with $location service

前端 未结 3 1678
离开以前
离开以前 2020-12-24 12:00

I am trying to create a simple unit test that tests my show function.

I get the following error:

TypeError: Object # has no method \'sh         


        
                      
相关标签:
3条回答
  • 2020-12-24 12:16

    Why don't you simply use a spyOn function?

    describe('OpponentsCtrl', function() {
    
        var location;
    
        beforeEach(module(function($provide) {
            $provide.factory('OpponentsCtrl', function($location){
                location = $location;
            });
        }));
    
        it('should change location when setting it via show function', inject(function() {    
            spyOn(location, 'path');    
            expect(location.path).toHaveBeenCalledWith('/new/path');
        }));
    });
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-24 12:25

    I prefer to mock location and services as then it's a unit (not integration) test:

    'use strict';
    describe('flightController', function () {
      var scope;
      var searchService;
      var location;
    
      beforeEach(module('app'));
      beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        mockSearchService();
        mockLocation();
        createController($controller);
      }));
    
      it('changes location to month page', function () {
        searchService.flightToUrl.and.returnValue('Spain/Ukraine/December/1');
        scope.showMonth();
        expect(location.url).toHaveBeenCalledWith('search/month/Spain/Ukraine/December/1');
      });
    
      function mockSearchService() {
        searchService = jasmine.createSpyObj('searchService', ['flightToUrl']);
      }
    
      function mockLocation() {
        location = jasmine.createSpyObj('location', ['url']);
      }
    
      function createController($controller) {
        $controller('flightController', {
          $scope: scope,
          searchService: searchService,
          $location: location
        });
      }
    });
    

    Cheers

    0 讨论(0)
  • 2020-12-24 12:26

    This is how my test ended up working.

    describe('OpponentsCtrl', function() {
        var scope, rootScope, ctrl, location;
    
        beforeEach(inject(function($location, $rootScope, $controller) {
            location = $location;
            rootScope = $rootScope;
            scope = $rootScope.$new();
            ctrl = $controller(OpponentsCtrl, {$scope: scope});
        }));
    
        it('should change location when setting it via show function', function() {
            location.path('/new/path');
            rootScope.$apply();
            expect(location.path()).toBe('/new/path');
    
            // test whatever the service should do...
            scope.show('/test');
            expect(location.path()).toBe('/test');
    
        });
    });
    
    0 讨论(0)
提交回复
热议问题