Skip to content

Commit

Permalink
add failing test: batches sync writes
Browse files Browse the repository at this point in the history
  • Loading branch information
dmaskasky committed Nov 17, 2024
1 parent 474e369 commit 5f04a05
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions tests/vanilla/dependency.test.tsx
Original file line number Diff line number Diff line change
@@ -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()
Expand Down Expand Up @@ -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)
})

0 comments on commit 5f04a05

Please sign in to comment.