232 lines
9.3 KiB
TypeScript
232 lines
9.3 KiB
TypeScript
import { createPinia, setActivePinia } from 'pinia'
|
|
import { readFileSync } from 'node:fs'
|
|
import { resolve } from 'node:path'
|
|
import { flushPromises, mount } from '@vue/test-utils'
|
|
import { createMemoryHistory, createRouter } from 'vue-router'
|
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
|
import { useAuthStore } from '@/core/auth/auth'
|
|
import { ApiResponseError } from '@/shared/api/http'
|
|
import LoginView from './LoginView.vue'
|
|
|
|
const loginSource = readFileSync(resolve(process.cwd(), 'src/modules/auth/pages/LoginView.vue'), 'utf8')
|
|
const formStub = {
|
|
template: '<form><slot /></form>',
|
|
setup(_: unknown, { expose }: { expose: (exposed: { validate: () => Promise<boolean> }) => void }) {
|
|
expose({ validate: async () => true })
|
|
},
|
|
}
|
|
|
|
function createMemoryStorage(): Storage {
|
|
const values = new Map<string, string>()
|
|
return {
|
|
get length() { return values.size },
|
|
clear: () => values.clear(),
|
|
getItem: (key) => values.get(key) ?? null,
|
|
key: (index) => [...values.keys()][index] ?? null,
|
|
removeItem: (key) => values.delete(key),
|
|
setItem: (key, value) => values.set(key, value),
|
|
}
|
|
}
|
|
|
|
describe('LoginView authentication lifecycle', () => {
|
|
beforeEach(() => {
|
|
vi.stubGlobal('localStorage', createMemoryStorage())
|
|
})
|
|
|
|
it('always renders a blank login form without demo credentials or hints', () => {
|
|
expect(loginSource).toContain("account: ''")
|
|
expect(loginSource).toContain("password: ''")
|
|
expect(loginSource).not.toContain('import.meta.env.DEV')
|
|
expect(loginSource).not.toContain('platform_admin')
|
|
expect(loginSource).not.toContain('ChangeMe123!')
|
|
expect(loginSource).not.toContain('demo-tip')
|
|
})
|
|
|
|
it('uses the shared blue-white theme and preserves the existing compact brand layout', () => {
|
|
expect(loginSource).toContain("import '@/styles/adminWorkbench.css'")
|
|
expect(loginSource).toContain('class="login-page admin-workbench"')
|
|
expect(loginSource).toContain('<h1 class="workbench-title">柏悦物流管理后台</h1>')
|
|
expect(loginSource).toContain('class="login-mobile-brand workbench-brand-mark"')
|
|
expect(loginSource).toContain('class="login-card workbench-panel"')
|
|
expect(loginSource).toContain('class="login-error workbench-notice workbench-tone" data-tone="rose"')
|
|
expect(loginSource).toContain('aria-label="平台员工登录"')
|
|
expect(loginSource).toContain('label-position="top" size="large"')
|
|
expect(loginSource).toContain('autocomplete="username" maxlength="100" autofocus')
|
|
expect(loginSource).toContain('aria-live="polite"')
|
|
expect(loginSource).not.toContain('var(--cc-navy)')
|
|
expect(loginSource).toContain('@media (max-width: 360px)')
|
|
expect(loginSource).not.toContain('让跨境物流管理')
|
|
})
|
|
|
|
it('initializes preview access after login and before redirecting', async () => {
|
|
const pinia = createPinia()
|
|
setActivePinia(pinia)
|
|
const auth = useAuthStore()
|
|
const access = useAccessPreviewStore()
|
|
const router = createRouter({
|
|
history: createMemoryHistory(),
|
|
routes: [
|
|
{ path: '/login', component: LoginView },
|
|
{ path: '/', component: { template: '<p>home</p>' } },
|
|
],
|
|
})
|
|
await router.push('/login')
|
|
await router.isReady()
|
|
|
|
const calls: string[] = []
|
|
vi.spyOn(auth, 'login').mockImplementation(async () => { calls.push('login') })
|
|
vi.spyOn(access, 'initializeAfterLogin').mockImplementation(() => { calls.push('access') })
|
|
vi.spyOn(router, 'replace').mockImplementation(async () => { calls.push('replace') })
|
|
const wrapper = mount(LoginView, {
|
|
global: {
|
|
plugins: [pinia, router],
|
|
stubs: {
|
|
'el-form': formStub,
|
|
'el-form-item': { template: '<label><slot /></label>' },
|
|
'el-input': { props: ['modelValue'], emits: ['update:modelValue'], template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' },
|
|
'el-button': { emits: ['click'], template: '<button type="button" @click="$emit(\'click\')"><slot /></button>' },
|
|
},
|
|
},
|
|
})
|
|
|
|
const inputs = wrapper.findAll('input')
|
|
await inputs[0]!.setValue('test_admin')
|
|
await inputs[1]!.setValue('password')
|
|
await wrapper.get('form').trigger('submit')
|
|
await flushPromises()
|
|
|
|
expect(calls).toEqual(['login', 'access', 'replace'])
|
|
})
|
|
|
|
it.each([
|
|
['/customers?page=2', '/customers?page=2'],
|
|
['/customers/reviews', '/customers/reviews'],
|
|
['//example.com', '/dashboard'],
|
|
['https://example.com', '/dashboard'],
|
|
[['/customers', '/orders/first-leg'], '/dashboard'],
|
|
[null, '/dashboard'],
|
|
])('sanitizes the post-login redirect %j to %s', async (redirect, expected) => {
|
|
const pinia = createPinia()
|
|
setActivePinia(pinia)
|
|
const auth = useAuthStore()
|
|
const router = createRouter({
|
|
history: createMemoryHistory(),
|
|
routes: [
|
|
{ path: '/login', component: LoginView },
|
|
{ path: '/', component: { template: '<p>home</p>' } },
|
|
],
|
|
})
|
|
await router.push({ path: '/login', query: { redirect } })
|
|
await router.isReady()
|
|
vi.spyOn(auth, 'login').mockResolvedValue()
|
|
const replace = vi.spyOn(router, 'replace').mockResolvedValue()
|
|
const wrapper = mount(LoginView, {
|
|
global: {
|
|
plugins: [pinia, router],
|
|
stubs: {
|
|
'el-form': formStub,
|
|
'el-form-item': { template: '<label><slot /></label>' },
|
|
'el-input': { props: ['modelValue'], emits: ['update:modelValue'], template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' },
|
|
'el-button': { emits: ['click'], template: '<button type="button" @click="$emit(\'click\')"><slot /></button>' },
|
|
},
|
|
},
|
|
})
|
|
|
|
const inputs = wrapper.findAll('input')
|
|
await inputs[0]!.setValue('test_admin')
|
|
await inputs[1]!.setValue('password')
|
|
await wrapper.get('form').trigger('submit')
|
|
await flushPromises()
|
|
|
|
expect(replace).toHaveBeenCalledWith(expected)
|
|
})
|
|
|
|
it('preserves the form and reports a recoverable error when login fails', async () => {
|
|
const pinia = createPinia()
|
|
setActivePinia(pinia)
|
|
const auth = useAuthStore()
|
|
const access = useAccessPreviewStore()
|
|
const router = createRouter({
|
|
history: createMemoryHistory(),
|
|
routes: [
|
|
{ path: '/login', component: LoginView },
|
|
{ path: '/customers', component: { template: '<p>customers</p>' } },
|
|
],
|
|
})
|
|
await router.push('/login')
|
|
await router.isReady()
|
|
vi.spyOn(auth, 'login').mockRejectedValue(new Error('network unavailable'))
|
|
const initialize = vi.spyOn(access, 'initializeAfterLogin')
|
|
const replace = vi.spyOn(router, 'replace')
|
|
const wrapper = mount(LoginView, {
|
|
global: {
|
|
plugins: [pinia, router],
|
|
stubs: {
|
|
'el-form': formStub,
|
|
'el-form-item': { template: '<label><slot /></label>' },
|
|
'el-input': { props: ['modelValue'], emits: ['update:modelValue'], template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' },
|
|
'el-button': { emits: ['click'], template: '<button type="button" @click="$emit(\'click\')"><slot /></button>' },
|
|
},
|
|
},
|
|
})
|
|
|
|
const inputs = wrapper.findAll('input')
|
|
await inputs[0]!.setValue('test_admin')
|
|
await inputs[1]!.setValue('password')
|
|
await wrapper.get('form').trigger('submit')
|
|
await flushPromises()
|
|
|
|
expect(wrapper.get('[role="alert"]').text()).toContain('登录失败,请检查账号和密码后重试')
|
|
expect(wrapper.get('[role="alert"]').text()).not.toContain('network unavailable')
|
|
expect(initialize).not.toHaveBeenCalled()
|
|
expect(replace).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('shows the backend credential error and diagnostic identifiers', async () => {
|
|
const pinia = createPinia()
|
|
setActivePinia(pinia)
|
|
const auth = useAuthStore()
|
|
const router = createRouter({
|
|
history: createMemoryHistory(),
|
|
routes: [
|
|
{ path: '/login', component: LoginView },
|
|
{ path: '/', component: { template: '<p>home</p>' } },
|
|
],
|
|
})
|
|
await router.push('/login')
|
|
await router.isReady()
|
|
vi.spyOn(auth, 'login').mockRejectedValue(new ApiResponseError(
|
|
'用户名或密码错误',
|
|
'A0401',
|
|
undefined,
|
|
null,
|
|
'request-login',
|
|
'trace-login',
|
|
))
|
|
const wrapper = mount(LoginView, {
|
|
global: {
|
|
plugins: [pinia, router],
|
|
stubs: {
|
|
'el-form': formStub,
|
|
'el-form-item': { template: '<label><slot /></label>' },
|
|
'el-input': { props: ['modelValue'], emits: ['update:modelValue'], template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />' },
|
|
'el-button': { emits: ['click'], template: '<button type="button" @click="$emit(\'click\')"><slot /></button>' },
|
|
},
|
|
},
|
|
})
|
|
|
|
const inputs = wrapper.findAll('input')
|
|
await inputs[0]!.setValue('platform_admin')
|
|
await inputs[1]!.setValue('incorrect-password')
|
|
await wrapper.get('form').trigger('submit')
|
|
await flushPromises()
|
|
|
|
const alert = wrapper.get('[role="alert"]').text()
|
|
expect(alert).toContain('用户名或密码错误')
|
|
expect(alert).toContain('request-login')
|
|
expect(alert).toContain('trace-login')
|
|
expect(alert).not.toContain('登录状态已失效')
|
|
})
|
|
})
|