I needed to control a read only property in a unit test and it gave me a bit of a headache to figure it out, so I thought I'd blog it--as I often do.
I'm writing unit tests for an Angular Component. This is oversimplified, but I was using content children to get a QueryList:
Later I had a method that looked for changes to the QueryList:
2// do stuff;
3).subscribe()
In my test I wanted to replace the Observable with my own so I could get access tot he Observer and control when the Observable result handler were fired.
If changes was a normal property I could just do this:
2 myLocalObserver = observer;
3});
But, I cannot do that for a read only property.
If this were set up with a get, but not a set, I'd be able to spyOnProperty:
2new Observable((observer) => {
3 myLocalObserver = observer;
4}));
But, TypeScript was not liking that because the property was set up using the readonly modifier.
What I had to do was use Object.assign():
2 changes: new Observable((observer) => {
3 myLocalObserver = observer;
4 }));
5}
And this gave me complete control over the read only changes property.