126 lines
2.6 KiB
TypeScript
126 lines
2.6 KiB
TypeScript
/**
|
|
* 测试环境设置
|
|
*/
|
|
|
|
import { vi } from 'vitest'
|
|
import { config } from '@vue/test-utils'
|
|
import ElementPlus from 'element-plus'
|
|
|
|
// 全局组件注册
|
|
config.global.plugins = [ElementPlus]
|
|
|
|
// 全局属性
|
|
config.global.config.globalProperties = {
|
|
$t: (key: string) => key, // 模拟国际化
|
|
$route: {
|
|
path: '/',
|
|
params: {},
|
|
query: {},
|
|
meta: {}
|
|
},
|
|
$router: {
|
|
push: vi.fn(),
|
|
replace: vi.fn(),
|
|
go: vi.fn(),
|
|
back: vi.fn(),
|
|
forward: vi.fn()
|
|
}
|
|
}
|
|
|
|
// 模拟全局对象
|
|
Object.defineProperty(window, 'matchMedia', {
|
|
writable: true,
|
|
value: vi.fn().mockImplementation(query => ({
|
|
matches: false,
|
|
media: query,
|
|
onchange: null,
|
|
addListener: vi.fn(), // deprecated
|
|
removeListener: vi.fn(), // deprecated
|
|
addEventListener: vi.fn(),
|
|
removeEventListener: vi.fn(),
|
|
dispatchEvent: vi.fn(),
|
|
})),
|
|
})
|
|
|
|
// 模拟 ResizeObserver
|
|
global.ResizeObserver = vi.fn().mockImplementation(() => ({
|
|
observe: vi.fn(),
|
|
unobserve: vi.fn(),
|
|
disconnect: vi.fn(),
|
|
}))
|
|
|
|
// 模拟 IntersectionObserver
|
|
global.IntersectionObserver = vi.fn().mockImplementation(() => ({
|
|
observe: vi.fn(),
|
|
unobserve: vi.fn(),
|
|
disconnect: vi.fn(),
|
|
}))
|
|
|
|
// 模拟 localStorage
|
|
const localStorageMock = {
|
|
getItem: vi.fn(),
|
|
setItem: vi.fn(),
|
|
removeItem: vi.fn(),
|
|
clear: vi.fn(),
|
|
}
|
|
global.localStorage = localStorageMock
|
|
|
|
// 模拟 sessionStorage
|
|
const sessionStorageMock = {
|
|
getItem: vi.fn(),
|
|
setItem: vi.fn(),
|
|
removeItem: vi.fn(),
|
|
clear: vi.fn(),
|
|
}
|
|
global.sessionStorage = sessionStorageMock
|
|
|
|
// 模拟 fetch
|
|
global.fetch = vi.fn()
|
|
|
|
// 模拟 URL.createObjectURL
|
|
global.URL.createObjectURL = vi.fn(() => 'mocked-url')
|
|
global.URL.revokeObjectURL = vi.fn()
|
|
|
|
// 模拟 Notification
|
|
global.Notification = vi.fn().mockImplementation(() => ({
|
|
close: vi.fn(),
|
|
}))
|
|
|
|
// 模拟 navigator
|
|
Object.defineProperty(navigator, 'clipboard', {
|
|
value: {
|
|
writeText: vi.fn().mockResolvedValue(undefined),
|
|
readText: vi.fn().mockResolvedValue(''),
|
|
},
|
|
writable: true,
|
|
})
|
|
|
|
Object.defineProperty(navigator, 'vibrate', {
|
|
value: vi.fn(),
|
|
writable: true,
|
|
})
|
|
|
|
// 模拟 document.execCommand
|
|
document.execCommand = vi.fn()
|
|
|
|
// 模拟 getSelection
|
|
global.getSelection = vi.fn().mockReturnValue({
|
|
toString: vi.fn().mockReturnValue(''),
|
|
removeAllRanges: vi.fn(),
|
|
addRange: vi.fn(),
|
|
})
|
|
|
|
// 模拟 console 方法(避免测试时输出过多日志)
|
|
global.console = {
|
|
...console,
|
|
log: vi.fn(),
|
|
debug: vi.fn(),
|
|
info: vi.fn(),
|
|
warn: vi.fn(),
|
|
error: vi.fn(),
|
|
}
|
|
|
|
// 设置测试环境变量
|
|
process.env.NODE_ENV = 'test'
|
|
process.env.VITE_APP_ENV = 'test'
|