Skip to content

Commit

Permalink
Add tests for useCache option
Browse files Browse the repository at this point in the history
  • Loading branch information
simoneb committed Oct 12, 2019
1 parent 7085eca commit 1dabd10
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 18 deletions.
33 changes: 15 additions & 18 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,23 @@ function executeRequestWithoutCache(config, dispatch) {
return request(config, dispatch)
}

export default function useAxios(
config,
options = { manual: false, useCache: true }
) {
function executeRequest(config, options, dispatch) {
if (options.useCache) {
return executeRequestWithCache(config, dispatch)
}

return executeRequestWithoutCache(config, dispatch)
}

export default function useAxios(config, options) {
if (typeof config === 'string') {
config = {
url: config
}
}

options = { manual: false, useCache: true, ...options }

const [state, dispatch] = React.useReducer(
reducer,
createInitialState(options)
Expand All @@ -129,26 +136,16 @@ export default function useAxios(

React.useEffect(() => {
if (!options.manual) {
options.useCache
? executeRequestWithCache(config, dispatch)
: executeRequestWithoutCache(config, dispatch)
executeRequest(config, options, dispatch)
}
}, [JSON.stringify(config)])

return [
state,
(configOverride, options = { useCache: false }) => {
if (options.useCache) {
return executeRequestWithCache(
{ ...config, ...configOverride },
dispatch
)
}
(configOverride, options) => {
options = { useCache: false, ...options }

return executeRequestWithoutCache(
{ ...config, ...configOverride },
dispatch
)
return executeRequest({ ...config, ...configOverride }, options, dispatch)
}
]
}
30 changes: 30 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,36 @@ describe('manual option', () => {
})
})

describe('useCache option', () => {
it('should use cache by default', async () => {
const { waitForNextUpdate } = renderHook(() => useAxios(''))

axios.mockResolvedValueOnce({ data: 'whatever' })

await waitForNextUpdate()

expect(axios).toHaveBeenCalledTimes(1)
expect(axios).toHaveBeenLastCalledWith(
expect.objectContaining({ adapter: expect.any(Function) })
)
})

it('should allow disabling cache', async () => {
const { waitForNextUpdate } = renderHook(() =>
useAxios('', { useCache: false })
)

axios.mockResolvedValueOnce({ data: 'whatever' })

await waitForNextUpdate()

expect(axios).toHaveBeenCalledTimes(1)
expect(axios).toHaveBeenCalledWith(
expect.not.objectContaining({ adapter: expect.any(Function) })
)
})
})

describe('configure', () => {
afterEach(() => resetConfigure())

Expand Down

0 comments on commit 1dabd10

Please sign in to comment.