这是我的代码
function guestDeviceManagerController(guestService, status) {
vm.initState = function() {
guestService.isUserAdmin(status.standardId).then(function(isAdmin) {
vm.isAdmin = isAdmin;
vm.template = vm.isAdmin ? vm.templates[0] : vm.templates[1];
}, function() {
//TODO: display user error
});
};
vm.initState();
}
我想知道如何模仿这些请求以及它应该在SpyOn()中完成的位置,如果是这样的话,我需要测试将响应返回为false和true。
进行了以下修改:
describe('guestDeviceManagerController Tests', function() {
'use strict';
var scope,
controller,
statusService,
guestService,
q;
beforeEach(function() {
module('mainApp');
module('mobileDevicesModule');
inject(function($rootScope, $controller, $q, _statusService_, _guestService_) {
scope = $rootScope.$new();
statusService = _statusService_;
guestService = _guestService_;
q = $q;
controller = $controller('guestController', {
$scope: scope,
guestService: guestService
});
});
});
it('Assert view that should render for admin', function() {
spyOn(guestService, 'isUserAdmin').and.returnValue(q.when(true));
scope.$apply();
controller.initState();
expect(controller.template.url).toEqual('app/mobile-devices/guest/admin/guest.html');
});
});
现在收到以下错误:错误:意外请求:GET http://localhost:34327/guest//IsAdmin
答案 0 :(得分:1)
使用true isAdmin结果测试成功路径:
spyOn(guestService, 'isUserAdmin').andReturn($q.when(true));
使用false isAdmin结果测试成功路径:
spyOn(guestService, 'isUserAdmin').andReturn($q.when(false));
测试错误路径:
spyOn(guestService, 'isUserAdmin').andReturn($q.reject());
请务必致电$rootScope.$apply()
以实际解决/拒绝承诺。
例如:
// spy the service:
spyOn(guestService, 'isUserAdmin').andReturn($q.when(true));
// instantiate the controller:
$controller('guestDeviceManagerController');
// resolve/reject the promises. This will cause the callback functions to be called
$rootScope.$apply();
// now test that the callback has done what it's supposed to do