diff --git a/tests/vanilla/dependency.test.tsx b/tests/vanilla/dependency.test.tsx index 8099eede493..a1693539c62 100644 --- a/tests/vanilla/dependency.test.tsx +++ b/tests/vanilla/dependency.test.tsx @@ -1,5 +1,9 @@ import { expect, it, vi } from 'vitest' import { atom, createStore } from 'jotai/vanilla' +import type { + INTERNAL_DevStoreRev4, + INTERNAL_PrdStore, +} from 'jotai/vanilla/store' it('can propagate updates with async atom chains', async () => { const store = createStore() @@ -346,3 +350,40 @@ it('can read sync derived atom in write without initializing', () => { // note: this is why write get needs to update deps expect(store.get(a)).toBe(2) }) + +it('batches sync writes', () => { + const a = atom(1) + a.debugLabel = 'a' + const b = atom(1) + b.debugLabel = 'b' + const fetch = vi.fn((va: number, vb: number) => va * 10 + vb) + const c = atom((get) => fetch(get(a), get(b))) + c.debugLabel = 'c' + const d = atom(null, (_, set) => { + set(a, (v) => ++v) + set(b, (v) => ++v) + }) + d.debugLabel = 'd' + const store = createStore() as INTERNAL_DevStoreRev4 & INTERNAL_PrdStore + const getAtomState = store.dev4_get_internal_weak_map().get + store.sub(a, () => {}) + store.sub(b, () => {}) + const cListener = vi.fn() + store.sub(c, cListener) + store.sub(d, () => {}) + const aState = getAtomState(a) as any + aState.label = 'a' + const bState = getAtomState(b) as any + bState.label = 'b' + const cState = getAtomState(c) as any + cState.label = 'c' + const dState = getAtomState(d) as any + dState.label = 'd' + cListener.mockClear() + fetch.mockClear() + store.set(d) + expect(cListener).toHaveBeenCalledOnce() + expect(fetch).toHaveBeenCalledOnce() + expect(fetch).toHaveBeenCalledWith(2, 3) + expect(store.get(c)).toBe(23) +})