简体   繁体   English

如何在角度2+中避免单元测试的依赖性

[英]how to avoid the dependencies hell with unit test in angular 2+

i see lots of examples about how to unit test simple components in angular 2+, but when it comes to test components who use services, it becomes a nightmare to maintain the test bed providers and imports. 我看到很多关于如何在角度2+中测试简单组件的例子,但是当涉及到测试使用服务的组件时,维护测试床提供者和导入变成了一场噩梦。 how can i avoid it ? 我怎么能避免呢?

for example i have myComponents, who uses myService, who uses HttpClient. 例如,我有myComponents,他使用myService,他使用HttpClient。 To test myComponent i must setup the providers for myService and HttpClient. 要测试myComponent,我必须为myService和HttpClient设置提供程序。 If i add an other service to the constructor of myService, i will have to edit ALL the testbeds of the cmoponents who use this service. 如果我将其他服务添加到myService的构造函数中,我将必须编辑使用此服务的cmoponents的所有测试页。

can't i tell the testbed to fetch the default dependencies for these modules? 我不能告诉testbed获取这些模块的默认依赖项吗?

The problem results from wrong testing methodology. 问题源于错误的测试方法。 Unit testing is about testing single units. 单元测试是关于测试单个单元。

In this scenario 在这种情况下

myComponents, who uses myService, who uses HttpClient. myComponents,使用myService,使用HttpClient。 To test myComponent i must setup the providers for myService and HttpClient. 要测试myComponent,我必须为myService和HttpClient设置提供程序。

it is myComponent unit that it tested. 它是我测试的myComponent单元。 This means that any other unit should be mocked or stubbed, including myService . 这意味着任何其他单元都应该被模拟或存根,包括myService

While this 虽然这个

fetch the default dependencies for these modules 获取这些模块的默认依赖项

is considered not unit but integration/e2e test. 被认为不是单位,而是整合/ e2e测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM