角度测试使用window.location.replace的服务方法 [英] Angular testing Service method with window.location.replace

查看:174
本文介绍了角度测试使用window.location.replace的服务方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Angular 4应用程序中,我需要测试一个服务的方法,它在某些时候调用同一服务的私有方法:



window.location.replace(url);



当测试到达该行时,karma-runner浏览器被重定向到 url 这当然不是我想要的。



如果我尝试间谍,我得到:



错误:< spyOn> :replace未声明为可写或没有setter



如何正确测试我的方法?

解决方案

location object is 只读属性,其属性也是只读的。



最好的测试友好策略是不直接使用本机对象,而是通过DI,因为testabiliry是DI的主要优点之一。



文档已经 DOCUMENT 提供者抽象,完全相同的窗口,与AngularJS $ window 服务类似:

  const WINDOW = new InjectionToken('window'); 
函数getWindow(){
返回窗口;
}

...
{提供:WINDOW,useFactory:getWindow}
...

...
构造函数(@Inject(WINDOW)公共窗口){
this.window.location.replace(...);
}
...

在此设置中 WINDOW 提供程序可以在测试中存根,并且可以对全局变量进行全面测试。



或者,可以为每个正在使用的全局创建提供程序。 / p>

In my Angular 4 application, I need to test a method of a Service which at some point it calls a private method of the same service having:

window.location.replace(url);

When the test reach that line, the karma-runner browser gets redirected to the url which of course is not what I want.

If I try to spy it, I get:

Error: <spyOn> : replace is not declared writable or has no setter

How can I correctly test my method?

解决方案

location object is read-only property, and its properties are read-only as well.

The best test-friendly strategy is to not use native objects directly but via DI, because testabiliry is one of main benefits of DI.

document already has DOCUMENT provider abstraction, the same can be done for window entirely, similarly to AngularJS $window service:

const WINDOW = new InjectionToken('window');
function getWindow() {
  return window;
}

...
{ provide: WINDOW, useFactory: getWindow }
...

...
constructor(@Inject(WINDOW) public window) {
  this.window.location.replace(...);
}
...

In this setup WINDOW provider can be stubbed in tests, and globals can be thoroughly tested.

Alternatively, providers can be created for each global in use.

这篇关于角度测试使用window.location.replace的服务方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆