Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. However, the TestBed.createComponent function takes an argument of type Type<T>. I'm unable to create a Type<T> from the passed in generic T argument.

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?

like image 576
Krishna Chaitanya Avatar asked Oct 16 '22 15:10

Krishna Chaitanya


1 Answers

One option you have is to use the Type<T> as a parameter to your function:

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>.

like image 57
Daniel W Strimpel Avatar answered Oct 20 '22 11:10

Daniel W Strimpel