I have a scenario to spy the protected property from the base class.
export class BaseClass {
protected property1: string;
}
export class InheritedClass extends BaseClass, OnInit {
ngOnInit() {
this.populateProperties();
}
populateProperties() {
this.property1 = "test";
}
}
I am trying to write the unit test for this but is returning property1
not found. What could be the issue?
describe('populateProperties', () => {
it('should assign the properties values', () => {
// arrange
const spy = spyOnProperty((component as any), 'property1');
// act
component.populateProperties();
// assert
expect(spy).toBeDefined();
});
});
It's an instance variable, not a function so therefore it cannot be spied upon.
Try this:
describe('populateProperties', () => {
it('should assign the properties values', () => {
// act
component.populateProperties();
// assert
expect((component as any).property1).toBeDefined();
});
});
I assume the any
is required because property1
is protected in the BaseClass but this is not best practice. You should only be testing the HTML/View, public methods, and public properties of your component.