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:

view plain print about
1@ContentChildren(MyComponent) contentChildren: QueryList<MyComponent>;

Later I had a method that looked for changes to the QueryList:

view plain print about
2// do stuff;

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:

view plain print about
1comp.contentChildren.changes = new Observable((observer) => {
2 myLocalObserver = observer;

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:

view plain print about
1spyOnProperty(comp.contentChildren, 'changes', 'get').and.returnValue(
2new Observable((observer) =>
3 myLocalObserver = observer;

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():

view plain print about
1comp.contentChildren = Object.assign(QueryList<MyComponent>, {
2 changes: new Observable((observer) =>
3 myLocalObserver = observer;
4 }));

And this gave me complete control over the read only changes property.