Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion web-v2/web/src/lib/store/auth/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export const refreshToken = createAsyncThunk('auth/refreshToken', async (data, {
throw new Error(err)
}

const { access_token, expires_in } = res.data
const { access_token, expires_in } = res // `expires_in ` is in seconds, default is 499

return { token: access_token, expiredIn: expires_in }
})
Expand Down
44 changes: 42 additions & 2 deletions web-v2/web/src/lib/store/auth/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,25 @@
* under the License.
*/

import { beforeEach, describe, expect, it } from 'vitest'
import authReducer, { getAuthMe, setAuthUser } from '@/lib/store/auth'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { configureStore } from '@reduxjs/toolkit'

import { loginApi } from '@/lib/api/auth'
import authReducer, { getAuthMe, refreshToken, setAuthUser } from '@/lib/store/auth'

// The store reaches `@/lib/utils/axios`, which imports the JSX provider in
// `@/lib/provider/session.js`. Mock the request layer so these tests stay
// independent of it.
vi.mock('@/lib/api/auth', () => ({
getAuthConfigsApi: vi.fn(),
getAuthMeApi: vi.fn(),
loginApi: vi.fn(),
basicLoginApi: vi.fn()
}))

vi.mock('@/lib/store/sys', () => ({
initialVersion: vi.fn(() => ({ type: 'sys/initialVersion/mock' }))
}))

describe('auth store', () => {
beforeEach(() => {
Expand Down Expand Up @@ -51,3 +68,26 @@ describe('auth store', () => {
expect(state.isServiceAdmin).toBe(false)
})
})

describe('refreshToken', () => {
beforeEach(() => {
localStorage.clear()
sessionStorage.clear()
vi.clearAllMocks()
})

it('reads the token from the response body, as the login flow does', async () => {
// `loginApi` resolves to the response body, not to the Axios envelope.
loginApi.mockResolvedValue({ access_token: 'refreshed-token', expires_in: 499 })

const store = configureStore({ reducer: { auth: authReducer } })

const action = await store.dispatch(refreshToken())

expect(action.type).toBe(refreshToken.fulfilled.type)
expect(action.payload).toEqual({ token: 'refreshed-token', expiredIn: 499 })
expect(store.getState().auth.authToken).toBe('refreshed-token')
expect(localStorage.getItem('accessToken')).toBe('refreshed-token')
expect(localStorage.getItem('expiredIn')).toBe('499')
})
})