我有一个服务,其主要职责是重定向到我们的登录页面,该页面是独立的,因为我们将登录作为服务进行。
function redirectToMembership() {
var returnURL = $location.host();
returnURL+="/#/Authorization";
$window.location.href=EnvironmentConfigConstants.membershipURL + "?ReturnURL="+returnURL;
}
它的作用是获取当前主机并将 /#/Authorization
附加到末尾,然后重定向到成员资格 URL,并将其作为 returnURL。
授权是一种状态,它将处理从成员身份返回的 session token 和用户 ID。
我的问题是:
我应该如何对此进行单元测试?
我有预感,我需要监视 $location.href 并验证它是否是使用当前位置调用的,但每当我触发 membershipService.redirectToMembership
时,phantomJS 就会崩溃。
到目前为止,这是我的测试内容:
describe('redirectToMembership', function () {
beforeEach(function () {
spyOn($location,'host').andReturn('localhost');
spyOn($location,'port').andReturn(80);
spyOn($window.location,'href');
});
it('should redirect to Membership (duh)', function () {
var success = false;
membershipService.redirectToMembership();
expect($window.location.href).toBe('this');
$rootScope.$digest();
}) ;
});
但是,这给了我两个错误:
'undefine' 不是一个函数(评估 spy On($location,'host').andReturn('localhost')')
并且“undefined”不是对象(正在评估“returnURL.indexOf”)
我做错了什么吗?
最佳答案
我不会关注 phantomjs 崩溃的原因,但这里的想法是模拟你的依赖项而不是实际实例,即模拟 $location
和 $window
和然后返回值作为您的测试期望。重定向如何发生、主机如何返回等......不应该是您的服务所关心的问题,因此只需模拟它们即可。
类似这样的事情:
describe('redirectToMembership', function () {
var $location,
$window = {location:{href:""}},
host="localhost",
port="80",
membershipService,
$rootScope;
beforeEach(function () {
//Set up mocks
module('myModule',function($provide){
//create a spy object with 2 functions
$location = jasmine.createSpyObj('location',['host', 'port']);
$location.host.and.returnValue(host);
$location.port.and.returnValue(port);
//Set the mock object created above
$provide.value('$location', $location) ;
//Set the mock object
$provide.value('$window', $window) ;
});
//get instances
inject(function(_membershipService_, _$rootScope_){
membershipService = _membershipService_;
$rootScope = _$rootScope_;
});
});
it('should redirect to Membership (duh)', function () {
var success = false;
membershipService.redirectToMembership();
expect($window.location.href).toBe(ExpectedContructedURL);
$rootScope.$digest(); //You may not need this
});
});
关于javascript - 如何对主要职责是重定向到应用程序外部页面的 Angular 服务进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307450/