spec文件中的组件声明,而不是将顶级模块加载到TestBed中 [英] Component declaration in spec files as opposed to loading the top-level module into TestBed

查看:145
本文介绍了spec文件中的组件声明,而不是将顶级模块加载到TestBed中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有顶级模块 AppModule 的Angular(4.x)应用程序,它声明了几个自定义组件,因此可以在模板中使用它们。

I have an Angular (4.x) application with a top-level module AppModule, which declares several custom components, so they can be used in templates.

然而,对于jasmine / karma测试,最常见的方法似乎是使用 BrowserDynamicTestingModule 并在<期间声明任何所需的自定义组件code> beforeEach ,例如:

However, for jasmine/karma tests the most common approach seems to be using BrowserDynamicTestingModule and declare any required custom components during beforeEach, e.g.:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ MyComponent, SomeDependedUponComponent ]
  })
  .compileComponents();
}));

考虑到我们无论如何都在模拟主应用程序的环境,为什么不用一个人来初始化testBed AppModule ,所以每个自定义组件都可用于所有测试?类似于:

Considering we're simulating the main application's environment anyway, why wouldn't one just initialize the testBed with AppModule, so every custom component is available to all tests? Something like:

getTestBed().initTestEnvironment(
  [BrowserDynamicTestingModule, AppModule],
  platformBrowserDynamicTesting()
);

如果我没有遗漏某些东西,这更接近主应用程序的设置,甚至减少样板单个规范/测试文件中的代码。 Orre有任何缺点,例如性能损失?

If I'm not missing something, this is much closer to the main application's setup and even reduces boilerplate code in individual spec/test files. Orre there any disadvantages, such as a performance penalty?

推荐答案

上述方法是错误的,因为这种方式测试是事实上的整合测试,虽然它们应该是单元测试。

The said approach is wrong because this way the tests are de facto integration tests, while they are supposed to be unit tests.

单元测试的目的是测试一个单元。添加额外的移动部件可防止其单独进行测试,并在其中一个单元出现故障时使故障排除变得复杂。使用隔离单元测试可以改善隔离度/ a>没有TestBed,虽然TestBed仍然需要测试DI注释。

The purpose of unit test is to test a single unit. Adding additional moving parts prevents it from being tested in isolation and complicates trouble solving when one of the units fails. The isolation can be improved with isolated unit tests without TestBed, although TestBed is still necessary to test DI annotations.

这种方法需要提供集成/ e2e测试以确保所有单元都正确在单元测试中测试并且可以真正互操作。

This approach requires to provide integration/e2e tests as well to be sure that all units were properly tested in unit tests and can really interoperate.

如果规格导致样板代码,可以通过正确的设置进一步改进,如图所示此处

If the specs result in boilerplate code, this can be further improved with proper setup, like is shown here.

这篇关于spec文件中的组件声明,而不是将顶级模块加载到TestBed中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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