How to correctly specify when testing a component in an Angular that which component has input data in generic type

Viewed 132

I want to test a component, which can accept array with a different types of data, for existence, but Typescript show me an error:

Error:(7, 18) TS2314: Generic type 'AppTableComponent<T>' requires 1 type argument(s).

My component file:

export class AppTableComponent<T> {
  @Input() data: T[];

  constructor() {}
}

Test file

describe('AppTableComponent', () => {
  let component: AppTableComponent;
  let fixture: ComponentFixture;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppTableComponent,
        MockComponent( PreloaderComponent ),
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(AppTableComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

How to resolve this error?

1 Answers

You need to specify a type argument, just as the error indicates.

As the actual type argument isn't meaningful in the test case you specified above, I would recommend using unknown for maximum safety.

let component: AppTableComponent<unknown>;

If a test involves assigning to the input, you would need to specify the type argument explicitly when calling TestBed.createComponent like so

 TestBed.createComponent<AppTableComponent<string>>(AppTableComponent);
Related