In this snippet, you will find my oninit method which I am instructed not to modify.
ngOnInit(): void {
this.setCustomizedValues();
this.sub = PubSub.subscribe('highlightEntity', (subId, entityIdentifier: string) => {
document.querySelector(entityIdentifier).classList.add('highlight');
setTimeout(() => {
document.querySelector(entityIdentifier).classList.remove('highlight');
}, 2000);
});
}
Below is a basic test setup for reference
describe('aComponent', () => {
let httpCallerServiceStub = jasmine.createSpyObj('httpCallerServiceStub', ['get']);
let fixture: ComponentFixture<aComponent>;
let componentInstance: aComponent;
localStorage.clear();
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [aComponent],
providers: [
{
provide: HttpCallerService,
useValue: httpCallerServiceStub
}],
imports: [CommonModule, CmcSpinnerModule, NgbModule],
}).compileComponents();
fixture = TestBed.createComponent(aComponent);
componentInstance = fixture.componentRef.instance;
fixture.autoDetectChanges();
});
describe('ngOnInit method', () => {
beforeEach(() => {
fixture.componentInstance.customized = {};
});
it('should initialize with minimum input', () => {
// Triggers ngOnInit
fixture.detectChanges();
expect(fixture.componentInstance.customized).toEqual({});
});
});
The issue arises where tests fail inconsistently due to 'classList' of null error
"message": "An error was thrown in afterAll\nTypeError: Cannot read property 'classList' of null\n at <Jasmine>\n
at webpack:///components/path/aComponent.ts:35:53
This error on line no. 35 in the oninit function, points to the following lines:
setTimeout(() => {
document.querySelector(entityIdentifier).classList.remove('highlight');
}, 2000);
I have a few questions regarding this situation:
Even after trying tick(2000) and fake async in a simple ngonit test, the random errors persist. How can I resolve this? (referred from this answer)
Is there something missing in my testbed configuration? Because even when I exclude the oninit test and check another function without fixture.detectChanges(), the same random error occurs.
Running tests using fdescibe results in passing all tests every time. The issue only emerges when I remove the 'f' from fdescribe and run all tests including other components as well.
Any guidance on resolving this dilemma would be greatly appreciated, as I have been stuck on this for the past 4 days.