Mobx-state-tree: [question] mocking out actions in a store

Created on 8 Feb 2018  路  8Comments  路  Source: mobxjs/mobx-state-tree

howdy,
I know there is already a question posted regarding dynamically mocking out actions in a store where it is mentioned that the action could be replaced on the store instance. I was trying to do this something like this:

Howdy,
I was wondering if you could provide and example of how one would replace an action with a jest mock function by replacing the action on the instance of the store directly. I tried this and was getting errors:

TypeError: Cannot assign to read only property '...funciton name.....' of object '[object Object]'

So for example if I had a store like this:

testStore = types.model('testStore', {
name: types.string
}).actions((self) => {
function setName(aName) {
self.name = aName;
}

return {
setName
};
});

And say I had a jest test something like this:

it('testSomething', () => {
let aStore = TestStore.create({name: 'fred'});
aStore.setName = jest.fn()
:
})

this code would give me the error noted above. What would be the way to replace the method would it be in the when doing the create?

Most helpful comment

Tada #690

All 8 comments

Yea, this also kinda annoys me. So what about respecting NODE_ENV === 'test' (which is set automatically by Jest) and disable these guards?

That would work for me....or even the ability to unprotect an action.

Ah, just as you have said it, I've realized I've seen that in the docs ... unprotect is an actual API function. I am not sure though if it unprotects actions as well ... https://github.com/mobxjs/mobx-state-tree/blob/master/API.md#unprotect

neah it doesn't I tried....it was unhappy :-) (unless I did something wrong hahahaha)

You are right, unprotect is actually pretty simple, it just changes a boolean for a runtime protection :D

For actions, it would indeed require modification, but it should be pretty simple. There is this line that adds properties for actions. For tests, it should just call addHiddenWritableProp instead and that should do the trick.

Would you like to try to make a PR for it? :)

certainly....would it be ok if I make the pr after work (haha....at work at the moment). Will give it a go in probably about 4 hrs :-). Appreciate it FredyC

Would love to see a PR for this as well @andrusek @FredyC
in the mean time @mweststrate suggested the following workaround.
In your test add the following

Object.defineProperty(
  store.relevantStore,
  "actionYouWantToSpyOn",
   { configurable: true, writeable: true, enumerable: false, value: yourSpyFunction }
)

This did the trick for me.

Tada #690

Was this page helpful?
0 / 5 - 0 ratings