如何对一个主要负责重定向到应用程序外部页面的Angular服务进行单元测试
How to unit test an Angular Service whose main responsibility is to redirect to a page outside of the application?
我有一个服务,其主要职责是重定向到我们的登录页面,这是分开的,因为我们做登录作为一个服务。
function redirectToMembership() {
var returnURL = $location.host();
returnURL+="/#/Authorization";
$window.location.href=EnvironmentConfigConstants.membershipURL + "?ReturnURL="+returnURL;
}
它所做的是获取当前主机并将/#/Authorization
附加到末尾,然后重定向到成员URL,并将其作为returnURL。
Authorization是一种状态,用于处理从成员关系返回的会话令牌和userID。
我的问题是:
我应该如何进行单元测试?
我有一种预感,我需要监视你的$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();
}) ;
});
然而,这给了我两个错误:
'undefined' is not a function (evaluating spyOn($location,'host').andReturn('localhost')')
和'undefined' is not an object (evaluating '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
});
});
相关文章:
- 如何在构建node-webkit应用程序后获取外部资源
- 如何从Node Webkit应用程序中退出外部CMD文件
- Cordova包装应用程序内部链接加载在应用程序中,外部链接加载在浏览器中
- 控制node.js应用程序's通过外部网站举办的活动
- 尝试将外部JS和CSS文件添加到我的rails应用程序中
- Angular:如何在外部浏览器中打开Angular变量-appgyver混合应用程序
- 如何检查我是否使用java服务登录到外部应用程序
- 如果外部应用程序更改了持久模型(服务器数据库),AngularJS 是否可以自动更新视图
- 聆听外部应用程序使用 jQuery 对元素所做的样式更改
- 如何要求 javascript 等待执行外部应用程序结束
- ASP.NET从Crystal Report获取变量,但未正确传输到外部应用程序
- 启动外部应用程序
- 使用外部应用程序调用Outlook
- 从外部应用程序到Spring Security的Ajax身份验证
- 如何在线发布Node.js服务器,以便外部应用程序始终可以访问它
- 如何在Cordova/Ionic中打开外部应用程序
- 在浏览器外运行外部应用程序,如BitTorrent
- 正在等待外部应用程序启动Javascript
- 在Opera中调用外部应用程序的NPAPI替代方案
- 用于调用外部应用程序的NPAPI替换(本机消息传递主机)无法工作