import { describe, it, expect, vi, beforeEach } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import ThemeSwitch from '@/components/ThemeSwitch.vue'
import { useThemeStore } from '@/store/theme'
// Mock @vueuse/core
vi.mock('@vueuse/core', () => ({
useStorage: vi.fn((key, defaultValue) => {
return { value: defaultValue }
}),
usePreferredDark: vi.fn(() => ({ value: false }))
}))
describe('ThemeSwitch Component', () => {
beforeEach(() => {
setActivePinia(createPinia())
vi.clearAllMocks()
})
const mountThemeSwitch = () => {
return mount(ThemeSwitch, {
global: {
plugins: [createPinia()],
stubs: {
'el-tooltip': {
template: '
',
props: ['effect', 'content', 'placement']
},
'el-button': {
template: '',
props: ['circle', 'text']
},
'el-icon': { template: '', props: ['size'] },
Moon: { template: 'Moon' },
Sunny: { template: 'Sunny' },
Setting: { template: 'Setting' }
}
}
})
}
describe('渲染', () => {
it('应该正确渲染主题切换组件', () => {
const wrapper = mountThemeSwitch()
expect(wrapper.find('.theme-switch').exists()).toBe(true)
})
it('应该显示两个按钮', () => {
const wrapper = mountThemeSwitch()
const buttons = wrapper.findAll('.switch-btn')
expect(buttons.length).toBe(2)
})
it('浅色模式下应该显示太阳图标', () => {
const wrapper = mountThemeSwitch()
expect(wrapper.find('.icon-sunny').exists()).toBe(true)
})
})
describe('主题切换', () => {
it('点击主题按钮应该能触发点击事件', async () => {
const wrapper = mountThemeSwitch()
const buttons = wrapper.findAll('.switch-btn')
expect(buttons.length).toBeGreaterThan(0)
// 验证按钮可以被点击
await buttons[0].trigger('click')
// 验证没有抛出错误
expect(true).toBe(true)
})
it('主题按钮应该存在', () => {
const wrapper = mountThemeSwitch()
const themeButton = wrapper.findAll('.switch-btn')[0]
expect(themeButton.exists()).toBe(true)
})
})
describe('设置按钮', () => {
it('点击设置按钮应该触发 openSettings 事件', async () => {
const wrapper = mountThemeSwitch()
const buttons = wrapper.findAll('.switch-btn')
await buttons[1].trigger('click')
expect(wrapper.emitted('openSettings')).toBeTruthy()
})
})
describe('提示信息', () => {
it('应该显示切换模式的提示', () => {
const wrapper = mountThemeSwitch()
expect(wrapper.findAll('.el-tooltip').length).toBeGreaterThan(0)
})
})
})