我正试图在路线上测试一些条件:
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(...)。那么它不是一个函数 at $ routeProvider.when.resolve.auth(public / app / app.js:14:86)
当我在测试之外运行时,解析会发现注入的RoomService很好。
你能明白为什么它不能解决RoomService吗?
答案 0 :(得分:1)
'然后'正在倒塌,你需要嘲笑,例如:
beforeEach(() => {
angular.mock.module(services, ($provide) => {
let RoomService = jasmine.createSpyObj('RoomService', ['checkIfRoomExists']);
RoomService.checkIfRoomExists.and.returnValue(
{
then: () => ({
catch: () => true
})
}
);
$provide.value('RoomService', RoomService);
});
});
然后你不需要注入RoomService,因为$ provide会为你做。然后你的间谍应该工作(我还没有测试过这个),因为.then()将被正确模拟。