Skip to content

Commit 71c14bf

Browse files
committed
share local state test
1 parent dfa373f commit 71c14bf

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

test/use-swr-local-mutation.test.tsx

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { act, render, screen, fireEvent } from '@testing-library/react'
22
import React, { useEffect, useState } from 'react'
33
import useSWR, { mutate, createCache, SWRConfig } from 'swr'
44
import { serialize } from '../src/utils/serialize'
5-
import { createResponse, sleep, nextTick as waitForNextTick } from './utils'
5+
import { createResponse, sleep, nextTick } from './utils'
66

77
describe('useSWR - local mutation', () => {
88
it('should trigger revalidation programmatically', async () => {
@@ -29,6 +29,33 @@ describe('useSWR - local mutation', () => {
2929
await screen.findByText('data: 1')
3030
})
3131

32+
it('should share local state when no fetcher is specified', async () => {
33+
const useSharedState = (key, initialData) => {
34+
const { data: state, mutate: setState } = useSWR(key, { initialData })
35+
return [state, setState]
36+
}
37+
38+
function Page() {
39+
const [name, setName] = useSharedState('name', 'huozhi')
40+
const [job, setJob] = useSharedState('job', 'gardener')
41+
42+
return (
43+
<span
44+
onClick={() => {
45+
setName('@huozhi')
46+
setJob('chef')
47+
}}
48+
>
49+
{name}:{job}
50+
</span>
51+
)
52+
}
53+
render(<Page />)
54+
const root = screen.getByText('huozhi:gardener')
55+
fireEvent.click(root)
56+
await screen.findByText('@huozhi:chef')
57+
})
58+
3259
it('should trigger revalidation programmatically within a dedupingInterval', async () => {
3360
let value = 0
3461

@@ -144,7 +171,7 @@ describe('useSWR - local mutation', () => {
144171
//mount
145172
await screen.findByText('data: 0')
146173

147-
await waitForNextTick()
174+
await nextTick()
148175
await act(() => {
149176
// mutate and revalidate
150177
return mutate('mutate-promise', createResponse(999), false)
@@ -167,7 +194,7 @@ describe('useSWR - local mutation', () => {
167194
//mount
168195
await screen.findByText('data: 0')
169196

170-
await waitForNextTick()
197+
await nextTick()
171198
await act(() => {
172199
// mutate and revalidate
173200
return mutate('mutate-async-fn', async () => createResponse(999), false)

0 commit comments

Comments
 (0)