Mocking read-only properties for a class

See original GitHub issue

Reading 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:closed
  • Created 7 years ago
  • Reactions:2
  • Comments:17 (2 by maintainers)

github_iconTop GitHub Comments

139reactions
cpojercommented, Dec 5, 2016

What about Object.defineProperty(store, 'doOneThing', {value: jest.fn()})?

73reactions
michaeljotacommented, Oct 16, 2018

You can use this now:

jest.spyOn(obj, 'property', 'get').mockReturnValue('mockedValue');
Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found