Skip to content

Commit

Permalink
chore: add optimization test spec (pmndrs#381)
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi authored Mar 25, 2021
1 parent dd64532 commit fa983b2
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 5 deletions.
25 changes: 20 additions & 5 deletions tests/basic.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -177,25 +177,40 @@ it('uses a write-only derived atom', async () => {

const Counter: React.FC = () => {
const [count] = useAtom(countAtom)
return <div>count: {count}</div>
return (
<div>
commits: {useCommitCount()}, count: {count}
</div>
)
}

const Control: React.FC = () => {
const [, increment] = useAtom(incrementCountAtom)
return <button onClick={() => increment()}>button</button>
return (
<>
<div>button commits: {useCommitCount()}</div>
<button onClick={() => increment()}>button</button>
</>
)
}

const { getByText, findByText } = render(
const { getByText } = render(
<Provider>
<Counter />
<Control />
</Provider>
)

await findByText('count: 0')
await waitFor(() => {
getByText('commits: 1, count: 0')
getByText('button commits: 1')
})

fireEvent.click(getByText('button'))
await findByText('count: 1')
await waitFor(() => {
getByText('commits: 2, count: 1')
getByText('button commits: 1')
})
})

it('only re-renders if value has changed', async () => {
Expand Down
41 changes: 41 additions & 0 deletions tests/optimization.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,44 @@ it('only relevant render function called (#156)', async () => {
getByText('count2: 1 (2)')
})
})

it('only render once using atoms with write-only atom', async () => {
const count1Atom = atom(0)
const count2Atom = atom(0)
const incrementAtom = atom(null, (_get, set, _arg) => {
set(count1Atom, (c) => c + 1)
set(count2Atom, (c) => c + 1)
})

const Counter: React.FC = () => {
const [count1] = useAtom(count1Atom)
const [count2] = useAtom(count2Atom)
const renderCount = useRef(0)
++renderCount.current
return (
<div>
count1: {count1}, count2: {count2} ({renderCount.current})
</div>
)
}

const Control: React.FC = () => {
const [, increment] = useAtom(incrementAtom)
return <button onClick={increment}>button</button>
}

const { getByText, findByText } = render(
<Provider>
<Counter />
<Control />
</Provider>
)

await findByText('count1: 0, count2: 0 (1)')

fireEvent.click(getByText('button'))
await findByText('count1: 1, count2: 1 (2)')

fireEvent.click(getByText('button'))
await findByText('count1: 2, count2: 2 (3)')
})

0 comments on commit fa983b2

Please sign in to comment.