How to unit test angularjs controller with $location service

前端 未结 3 1680
离开以前
离开以前 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: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

提交回复
热议问题