简体   繁体   English

角度单元测试:使用泛型来创建组件

[英]Angular Unit Testing: Using Generics to Create Component

I am trying to create a generic wrapper around TestBed.createComponent , which takes a type argument and creates the component for that type. 我试图在TestBed.createComponent周围创建一个通用的包装器,它接受一个类型参数并为该类型创建组件。 However, the TestBed.createComponent function takes an argument of type Type<T> . 但是, TestBed.createComponent函数采用Type<T>的参数。 I'm unable to create a Type<T> from the passed in generic T argument. 我无法从传入的泛型T参数创建Type<T>

 export function createTestHarness<T>(): TestHarness<T> { let component: T; let fixture: ComponentFixture<T>; fixture = TestBed.createComponent<T>(**PROBLEM AREA**); component = fixture.componentInstance; fixture.detectChanges(); return new TestHarness<T>(component, fixture); } 

Is there a way to derive a Type<T> from the type passed in? 有没有办法从传入的类型派生Type<T>

Generics only exists at compile time and not at runtime. 泛型仅在编译时存在,而不在运行时存在。 So you can not derive the type of T. 所以你不能得出T的类型。

Get type of generic parameter 获取通用参数的类型

One option you have is to use the Type<T> as a parameter to your function: 您可以选择使用Type<T>作为函数的参数:

function createTestHarness<T>(type: Type<T>): TestHarness<T> {
  let component: T;
  let fixture: ComponentFixture<T>;

  fixture = TestBed.createComponent<T>(type);
  component = fixture.componentInstance;
  fixture.detectChanges();

  return new TestHarness<T>(component, fixture);
}

With the following usage: 具有以下用途:

const harness = createTestHarness(TestComponent);

Which will return a TestHarness<TestComponent> . 这将返回TestHarness<TestComponent>

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

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