【问题标题】:Angular testing: why put component under test in providers?角度测试:为什么要在提供者中测试组件?
【发布时间】:2019-01-17 16:57:10
【问题描述】:

Angular docs 中有一个示例,其中正在测试的组件与依赖服务一起放置在TestBed.configureTestingModule 的提供程序部分中。然后他们使用TestBed.get 而不是TestBed.createComponent 来访问组件:

app/welcome/welcome.component.spec.ts(仅限类设置)

beforeEach(() => {
  TestBed.configureTestingModule({
    // provide the component-under-test and dependent service
    providers: [
      WelcomeComponent,
      { provide: UserService, useClass: MockUserService }
    ]
  });
  // inject both the component and the dependent service.
  comp = TestBed.get(WelcomeComponent);
  userService = TestBed.get(UserService);
});

我看到的大多数其他文档和教程都将组件放在声明下。

我什么时候想在提供程序中测试组件?为什么?

【问题讨论】:

  • 所以,我测试了这种方法,它的工作原理......令人惊讶。好问题。
  • injector 将创建与服务相同的组件。

标签: angular typescript unit-testing


【解决方案1】:

在文档中提到如果component-under-test 有一些DI,那么我们需要像这样创建组件。它将创建组件的实例,类似于创建服务实例的方式。您可以使用TestBed.get(ComponentName) 获取此组件并测试该组件。

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2020-10-16
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多