I have a component that will contain many input fields and I am wanting to test that these fields are all correctly coded. Eventually, I will want to test other properties related to these inputs (e.g. visibility, related label's 'for' attributes etc.) and so I was am trying to create a generic testing method that can be used to run all the tests against a specific input.
I have created a class to hold the test information and custom methods, but moving the test code into this class makes the test not work as the parameter held by the class (set in the constructor) is null. I suspect this is something to do with the order that the code is executed, but I don't understand why extracting the code into a separate method breaks it.
My spec.ts
file looks like
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PropertySearchComponent } from './property-search.component';
class DCTestHarness<TComponent>{
constructor(
private component: TComponent | undefined = undefined,
private fixture: ComponentFixture<TComponent> | undefined = undefined
){}
testInput(inputName: string){
it(inputName + ' input', () => {
const input: Element = this.fixture?.debugElement?.nativeElement?.querySelector(`input[name="${inputName}"]`);
expect(input).toBeDefined();
})
}
}
describe('PropertySearchComponent', () => {
let component: PropertySearchComponent;
let fixture: ComponentFixture<PropertySearchComponent>;
let dcHarness: DCTestHarness<PropertySearchComponent> = new DCTestHarness<PropertySearchComponent>();
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ PropertySearchComponent ]
})
.compileComponents();
fixture = TestBed.createComponent(PropertySearchComponent);
component = fixture.componentInstance;
dcHarness = new DCTestHarness<PropertySearchComponent>(component, fixture);
fixture.detectChanges();
});
/* This works */
it('should create', () => {
expect(component).toBeTruthy();
});
/* This works */
it('pdCode input inline', () => {
const input: Element = fixture.debugElement.nativeElement.querySelector(`input[name="pdCode"]`);
expect(input).toBeDefined();
})
/* This doesn't work */
dcHarness.testInput('pdCode'); //fixture is undefined