2016-11-22 80 views
0

我想測試一些條件,我有一個解決途徑:測試路線的決心角

app.js

$routeProvider.when('/:room/login/', { 
     templateUrl: '/app/login/login.html', 
     controller: 'LoginCtrl', 
     resolve: { 
      auth: ['$q', 'RoomService', 'LoginService', '$location', '$route', function ($q, RoomService, LoginService, $location, $route) { 
       return RoomService.checkIfRoomExists($route.current.params.room).then(function (success) { 
        if (success === false) { 
         $location.path('/notFound'); 
         $location.replace(); 
         return $q.reject(); 
        } 
        else 
        { 
         return LoginService.isUserLoggedIn().then(function (isloggedin) { 
           if (isloggedin === true) { 
            var currentPath = $location.path(); 
            $location.path($route.current.params.room); 
            $location.replace(); 
            return $q.reject(); 
           } 
          }, function (err) { 
           return $q.reject(err); 
          }) 
        } 
       }, 
        function (err) { 
         return $q.reject(err); 
        }) 
      }] 
     } 
    }) 

這是我的測試:

describe('LoginRoute', function() 
    { 
     beforeEach(module('corpusRoom')); 

     var mockHttp, location, route, rootScope, loginService, roomService; 

     beforeEach(inject(function($httpBackend, $location, _$route_, $rootScope, LoginService, RoomService){ 
      mockHttp = $httpBackend; 
      location = $location; 
      route = _$route_; 
      rootScope = $rootScope; 
      spyOn(LoginService, 'isUserLoggedIn'); 
      spyOn(RoomService, 'checkIfRoomExists'); 
      loginService = LoginService; 
      roomService = RoomService; 
     })); 

     it('should check if room exists', function(done) 
     { 
      location.path('/anyroom/login'); 
      rootScope.$apply(); 
      expect(roomService.checkIfRoomExists).toHaveBeenCalled(); 
      done(); 
     }); 
}); 

但是當我運行這在Karma報告了這個錯誤

TypeError: RoomService.checkIfRoomExists(...).then is not a function at $routeProvider.when.resolve.auth (public/app/app.js:14:86)

該resol當我在測試之外運行時,ve發現注入的RoomService很好。

你能看出爲什麼它無法解析RoomService嗎?

回答

1

這是「然後」被掉落下來,你需要模擬,因此,例如:

beforeEach(() => { 
    angular.mock.module(services, ($provide) => { 
    let RoomService = jasmine.createSpyObj('RoomService', ['checkIfRoomExists']); 
    RoomService.checkIfRoomExists.and.returnValue(
     { 
     then:() => ({ 
      catch:() => true 
     }) 
     } 
    ); 
    $provide.value('RoomService', RoomService); 
    }); 
}); 

這樣你就不會需要注入提供客房服務,爲$提供會爲你做它。那麼你間諜應該工作(但我還沒有測試過),因爲.then()將被正確模擬。