I am trying to test Angular components with jest. One component initializes an inherited (previously undefined) variable in its constructor. When running the application it works as expected. When I run my test and call MockRender(MyComponent), the variable is initialized in the constructor but when the ngOnInit-Block is reached, it is null (only for testing, not when running the application).
I tried replicating this error with a minimal example, but an initialized variable keeps its value between constructor call and ngOnInit as expected.
constructor() {
super()
this.myVariable = "i am initialized"
//successfully set in minimum example and test
console.log("constructed " + this.myVariable)
}
ngOnInit(): void {
//successfully set in minimum example (including test for minimum example)
// and running application but null in test for original component
console.log("ngOnInit " + this.myVariable)
super.ngOnInit()
}
When I completely remove the initialization of the variable from my constructor, it is still changed from undefined
to null
between constructor-call and ngOnInit.
From my understanding, when a component is set up, the constructor is called and then ngOnInit, so nothing should be able to interfere between those two calls. In addition, I can’t find anything in the code that might set the variable to null.
What might be the cause for a variable being reset to null
between constructor-call and ngOnInit only when testing, not when running the application?