Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chore: improve tests for cache provider #1369

Merged
merged 1 commit into from
Aug 24, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions test/use-swr-cache.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { act, fireEvent, render, screen } from '@testing-library/react'
import React, { useState } from 'react'
import useSWR, { useSWRConfig, SWRConfig, mutate as globalMutate } from 'swr'
import { sleep, createKey, nextTick, focusOn } from './utils'
import { sleep, createKey, createResponse, nextTick, focusOn } from './utils'

describe('useSWR - cache provider', () => {
let provider
Expand Down Expand Up @@ -43,8 +43,7 @@ describe('useSWR - cache provider', () => {
it('should be able to read from the initial cache with updates', async () => {
const key = createKey()
const renderedValues = []
const fetcher = () =>
new Promise(res => setTimeout(res, 100, 'updated value'))
const fetcher = () => createResponse('updated value', { delay: 10 })

function Page() {
const { data } = useSWR(key, fetcher)
Expand Down Expand Up @@ -352,22 +351,21 @@ describe('useSWR - cache provider', () => {
})

it('should return the cache instance from the useSWRConfig', async () => {
const cache = new Map()
let cache2
let cache
function Foo() {
cache2 = useSWRConfig().cache
cache = useSWRConfig().cache
return null
}
function Page() {
return (
<SWRConfig value={{ provider: () => cache }}>
<SWRConfig value={{ provider: () => provider }}>
<Foo />
</SWRConfig>
)
}

render(<Page />)
expect(cache).toBe(cache2)
expect(provider).toBe(cache)
})

it('should retain the correct cache hierarchy', async () => {
Expand Down Expand Up @@ -404,7 +402,27 @@ describe('useSWR - cache provider', () => {
await screen.findByText('data,data,data')
})

it('should clear cache between tests', async () => {
expect(provider.size).toBe(0)
it('should not recreate the cache if rerendering', async () => {
const createCacheProvider = jest.fn()
let rerender

function Page() {
rerender = useState({})[1]
return (
<SWRConfig
value={{
provider: () => {
createCacheProvider()
return provider
}
}}
/>
)
}

render(<Page />)
expect(createCacheProvider).toBeCalledTimes(1)
act(() => rerender({}))
expect(createCacheProvider).toBeCalledTimes(1)
})
})