Nov 15, 2021

Jasmine in Angular Unit-test: Modify a Read-only value with "Object.definedProperty"

If you are using Typescript and when you're not as well-versed with it (like I do), then surely you'll come into type issue from time to time.

If unlucky, eslint will also give you some headache time during your development work too, but that's good sign that you are learning.

Problems

Modifying a read-only value in Angular Unit-Test (*.spec.ts) files will give you warning like below:

Cannot assign a value to a read-only property even on Unit Test script

the routerSpy is a mocked Router from '@angular/router'.

let routerSpy: jasmine.SpyObj<Router>;


Solution

With the help from native Javascript Object.defineProperty(), we can set value manually through method below:

Set value through Object.defineProperty


No comments:

Post a Comment

Hey, thank you for spending time leaving some thoughts, that would be really helpful as encouragement for us to write more quality articles! Thank you!