Skip to content

Commit

Permalink
Merge pull request #2 from pmndrs/test-atom-with-storage
Browse files Browse the repository at this point in the history
add test for atomWithStorage
  • Loading branch information
sandren authored May 9, 2021
2 parents 5e81d18 + 904abc8 commit 77e45b6
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/utils/atomWithStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ type Storage<Value> = {
}

const defaultStorage: Storage<unknown> = {
getItem: (key: string) => {
getItem: (key) => {
const storedValue = localStorage.getItem(key)
if (storedValue === null) {
throw new Error('no value stored')
}
return JSON.parse(storedValue)
},
setItem: (key, newValue: unknown) => {
setItem: (key, newValue) => {
localStorage.setItem(key, JSON.stringify(newValue))
},
}
Expand Down
47 changes: 47 additions & 0 deletions tests/utils/atomWithStorage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import React, { Fragment } from 'react'
import { fireEvent, render } from '@testing-library/react'
import { Provider as ProviderOrig, useAtom } from '../../src/index'
import { atomWithStorage } from '../../src/utils'

const Provider = process.env.PROVIDER_LESS_MODE ? Fragment : ProviderOrig

const storageData: Record<string, number> = {
count: 10,
}
const dummyStorage = {
getItem: (key: string) => {
if (!(key in storageData)) {
throw new Error('no value stored')
}
return storageData[key]
},
setItem: (key: string, newValue: number) => {
storageData[key] = newValue
},
}

it('simple count', async () => {
const countAtom = atomWithStorage('count', 1, dummyStorage)

const Counter: React.FC = () => {
const [count, setCount] = useAtom(countAtom)
return (
<>
<div>count: {count}</div>
<button onClick={() => setCount((c) => c + 1)}>button</button>
</>
)
}

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

await findByText('count: 10')

fireEvent.click(getByText('button'))
await findByText('count: 11')
expect(storageData.count).toBe(11)
})

0 comments on commit 77e45b6

Please sign in to comment.