I'm talking about Typescript but it could be a generic question...
How to test that a property is readonly?
I mean, it's a language feature so seems quite obvious that if I declare a property as readonly no one can reassign it as the code won't compile, but without any test, no one assure me that I can safely change the code, make the property writable and then modify it... So how can I write a unit test that fails if the property is writable?
Can you write such a test? Yes; using plain javascript that calls the javascript code your Typescript code transpiles to.
However, should you write such a test? No.
One of the main reasons to use transpiled and/or compiled languages such Typescript is that the compiler takes on part of the burden of correctness. Specifically, the correctness of the guarantees the language offers.
So sit back and enjoy the heavy lifting the compiler does for you.
One caveat: If your project uses a mix of javascript and Typescript then you might want to consider it, but then it is still probably better to spend that time rewriting the javascript bits to Typescript.
Edit:
Look at the situation from the perspective of the test: what would be necessary for the test to pass now and fail at some later time due to regression?
Well, since the code won't compile if some later edit modifies the readonly
property, this edit must include removing the readonly
from the property.
But having seen and rejected this guard, what is to stop the editor from removing the test that now fails as well?
So in a sense, the readonly
modifier is the test.