2

Is it possible to test an Angular Generic Component?

As an example, if I have

@Component({
    ...
})
export class MyComponent<T> implements OnInit {
   public constructor(
      private context: T
   );
}

Where T can be any number of classes.

Then eventually I want to write a Jasmine test, but I am not able to determine the proper syntax for when creating the test fixture:

fixture = TestBed.createComponent(MyComponent<MyTestObject>);

It is here that TSLint complains:

Value of type 'typeof MyComponent' is not callable. Did you mean to include new?

It clearly thinks that I need a constructor (?), but is unclear how or where to implement that.

Is what I am attempting even possible? I can find examples of generic components. I can't find examples on setting up a test fixture / component

2 Answers 2

5

The TestBed.createComponent function in itself is generic and returns a componentFixture, so that is where you should apply the generic. For your use-case you should do:

fixture = TestBed.createComponent<MyComponent<MyTestObject>>(MyComponent);

Remember to have declared your fixture as

let fixture: ComponentFixture<MyComponent<MyTestObject>>;
Sign up to request clarification or add additional context in comments.

Comments

3

I imagine that TestBed.createComponent() expects a javascript class as an argument. MyComponent<MyTestObject> is not valid javascript.

Perhaps you intended to put TestBed.createComponent(MyComponent as typeof MyComponent<MyTestObject>) (or maybe the proper syntax is MyComponent as (typeof MyComponent)<MyTestObject> -- I'm not sure).

Alternatively, if TestBed#createComponent() is generic, you'd probably want to do TestBed.createComponent<MyComponent<MyTestObject>>(MyComponent).

1 Comment

This doesn't work =) still interested in this matter

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.