I developed an application with Angular (2+) and now I'm testing every single application .ts
file to get a good percentage of code coverage. I have a problem. I'm testing a component that in the ngOnInit
life cycle method uses the document
object to refer to some elements of the HTML template. This is a code sample:
export class MyComponent implements OnInit {
element;
ngOnInit() {
this.element = document.getElementById('myElementId');
this.element.className = 'blur'
}
}
where myElementId
is a <div>
element of my template. As for the test, here's part of the code:
describe('MyComponent Tests', () => {
let fixture: ComponentFixture<MyComponent>;
let component: MyComponent;
let rootElement: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [MyComponentModule, RouterTestingModule],
providers: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
})
});
});
beforeEach(() => {
fixture = TestBed.createComponent(IndexPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
rootElement = fixture.debugElement;
});
it("Should created", fakeAsync(() => {
expect(component).toBeTruthy();
}));
});
When I start the test it gives me a FAILED result with this error: Cannot set property 'className' of null. Basically the line fixture.detectChanges()
activates the ngOnInit()
method of my component, but it is as if the component instance on the test file is not linked with the HTML template!. For this reason the line this.element.className = 'blur'
, fundamental for the functioning of the component, is evaluated as if it were a null pointer. How can I solve this problem and test the component well?
Aucun commentaire:
Enregistrer un commentaire