【发布时间】:2013-12-13 16:19:16
【问题描述】:
我有以下服务:
angular.module("services")
.factory("whatever", function($window) {
return {
redirect: function() {
$window.location.replace("http://www.whatever.com");
}
};
});
如何在单元测试中模拟$window对象以防止在运行测试时重新加载页面?
我尝试过使用
spyOn($window.location, 'replace').andReturn(true);
,但它不起作用(仍然出现"Some of your tests did a full page reload!" 错误)并且
$provide.value('$window', {location: {replace: jasmine.createSpy()}})
,但我收到一个错误 (Error: [ng:areq] Argument 'fn' is not a function, got Object),堆栈跟踪仅指向 Angular 自己的源,所以它不是很有帮助...
【问题讨论】:
-
我也遇到了同样的问题。你找到解决办法了吗?
-
PaulL 提供的将
$window.location包装在单独的服务中的解决方案实际上工作得很好。还没有尝试过 LostInComputer 的解决方案。
标签: javascript unit-testing angularjs mocking angularjs-service