中使用单元测试避免依赖地狱

中使用单元测试避免依赖地狱

本文介绍了如何在Angular 2+中使用单元测试避免依赖地狱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了很多有关如何在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.how can i avoid it ?

例如我有myComponents,谁使用myService,谁使用HttpClient.要测试myComponent,我必须为myService和HttpClient设置提供程序.如果将其他服务添加到myService的构造函数中,则必须编辑使用该服务的cmoponent的所有测试平台.

for example i have myComponents, who uses myService, who uses HttpClient.To test myComponent i must setup the providers for myService and 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.

我不能告诉测试平台获取这些模块的默认依赖项吗?

can't i tell the testbed to fetch the default dependencies for these modules?

推荐答案

问题是由错误的测试方法导致的.单元测试是关于测试单个单元.

The problem results from wrong testing methodology. Unit testing is about testing single units.

在这种情况下

它是它测试的 myComponent 单元.这意味着任何其他单元都应被模拟或存根,包括 myService .

it is myComponent unit that it tested. This means that any other unit should be mocked or stubbed, including myService.

与此同时

被认为不是单元而是集成/端到端测试.

is considered not unit but integration/e2e test.

这篇关于如何在Angular 2+中使用单元测试避免依赖地狱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:43