如何嘲笑在AngularJS单元测试$ window.location.replace? [英] How to mock $window.location.replace in AngularJS unit test?
问题描述
我已经得到了以下服务:
I've got the following service:
angular.module("services")
.factory("whatever", function($window) {
return {
redirect: function() {
$window.location.replace("http://www.whatever.com");
}
};
});
如何嘲笑 $窗口
对象单元测试prevent运行测试时重新加载页面?
How to mock $window
object in unit test to prevent reloading the page when running tests?
我试图用
spyOn($ window.location的,'取代')andReturn(真);
,但它没有工作(仍然有您的一些测试做了全面的重新加载页面!
误差)以及
, but it didn't work (still got "Some of your tests did a full page reload!"
error) and
$ provide.value('$窗口',{位置:{替换:jasmine.createSpy()}})
,但我得到了一个错误(错误:[NG:AREQ]参数FN是不是一个函数,得到了对象
)与堆栈跟踪仅指向角自己的源代码,所以这是不是非常有帮助...
, but I was getting an error (Error: [ng:areq] Argument 'fn' is not a function, got Object
) with stack trace pointing only to angular own source, so it wasn't very helpful...
推荐答案
在Chrome浏览器(没有测试inother浏览器),location.replace是只读所以spyOn无法取代它。
In Chrome (didn't test inother browsers), location.replace is readonly so spyOn wasn't able to replace it.
$ provide.value
应该工作。东西必须在您的code错了地方。
$provide.value
should work. Something must be wrong somewhere in your code.
下面是一个工作单元测试
Here is a working unit test
describe('whatever', function() {
var $window, whatever;
beforeEach(module('services'));
beforeEach(function() {
$window = {location: { replace: jasmine.createSpy()} };
module(function($provide) {
$provide.value('$window', $window);
});
inject(function($injector) {
whatever = $injector.get('whatever');
});
});
it('replace redirects to http://www.whatever.com', function() {
whatever.redirect();
expect($window.location.replace).toHaveBeenCalledWith('http://www.whatever.com');
});
});
这篇关于如何嘲笑在AngularJS单元测试$ window.location.replace?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!