Mocking read-only properties for a class
See original GitHub issueReading from the documentation, it wasn’t clear how I could mock a single class instance method when it’s on read-only mode. I’m using MobX for our state store so I have little control over class methods:
class ViewStore {
@observable field = null;
@action doOneThing = () => {
this.field = 'one';
}
@action doAnotherThing = () => {
this.doOneThing();
}
}
const store = new ViewStore();
If I want to write a test for store.doAnotherThing and test that store.doOneThing gets called once, I can’t do it with store.doOneThing = jest.fn() as it’s a read-only property (TypeError: Cannot assign to read only property 'doOneThing' of object '#<ViewStore>').
With Sinon’s spy I could do something like spy(store, 'doOneThing'); but I haven’t figured out how to accomplished this with Jest.
Any tips?
Issue Analytics
- State:
- Created 7 years ago
- Reactions:2
- Comments:17 (2 by maintainers)
Top Results From Across the Web
How to Setup a readonly property with Moq? - Stack Overflow
I'm talking about scenario when you actually need to mock an object that sets its readonly property in the constructor. Then you want...
Read more >How to mock read-only property in jest | by kozo yamagata
The function checks if that the size is lower than 10,000 bytes, and returns boolean. Therefore, in the test case, we have to...
Read more >C# – How to mock class with readonly property - iTecNote
Any idea in Moq for a class with readonly modifier : Class myClass { private int id; public int Id{ get {return id;}}...
Read more >Properties - Unit Testing in C#
In case a property of the mock should behave like an automatic property, developers can instruct Moq to track the values passed to...
Read more >Mock for readonly field - Google Groups
Their playerId and brandId produced seems to be generated randomly. How to mock a class with all readonly property and given assigned value....
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
What about
Object.defineProperty(store, 'doOneThing', {value: jest.fn()})?You can use this now: