Best pactices for testing derived #347
-
Hey team, I'm loving valtio and the great DX it provides. I'm running into some issues testing my stores and I was curious if I was doing something wrong or approaching the problem incorrectly. I have a derived store where I am trying to test some computed values. Here's some example code that's failing in jest. it('test', () => {
const store = proxy({
num: 1
});
const derived = derive({
isTwo: (snap) => snap(store).num === 2
},
{
proxy: store
})
subscribe(derived, () => {
console.log("changed store", derived)
})
expect(derived.num).toEqual(1) //pass
expect(derived.isTwo).toEqual(false) //pass
derived.num = 2;
expect(derived.isTwo).toEqual(true) //false, expected 'true' recevied 'false'
}) console output:
I tried playing around with jest timers, but to no avail. Is there better approach for testing derived proxies? I've tested the above code on |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The trick is valtio automatically batches multiple mutations and notification happens in async. await waitFor(() => {
expect(derived.isTwo).toEqual(true)
}) Alternatively, you can disable the batching if that's what you'd expect: const derived = derive({
isTwo: (snap) => snap(store).num === 2
},
{
proxy: store,
sync: true // to avoid batching
}) Hope it helps. |
Beta Was this translation helpful? Give feedback.
The trick is valtio automatically batches multiple mutations and notification happens in async.
So, you need to test it in async:
Alternatively, you can disable the batching if that's what you'd expect:
Hope it helps.