/** * useECharts Composable 测试 */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { ref } from 'vue' import { useECharts } from '@/composables/useECharts' // Mock echarts vi.mock('echarts', () => ({ default: { init: vi.fn(() => ({ setOption: vi.fn(), resize: vi.fn(), dispose: vi.fn(), on: vi.fn(), off: vi.fn(), showLoading: vi.fn(), hideLoading: vi.fn(), clear: vi.fn(), getDataURL: vi.fn(), })), }, })) describe('useECharts', () => { let chartRef: Ref beforeEach(() => { // 创建 mock DOM 元素 const mockElement = document.createElement('div') chartRef = ref(mockElement) }) afterEach(() => { vi.clearAllMocks() }) it('initializes chart correctly', () => { const { chart, isReady } = useECharts(chartRef) // 检查图表实例是否创建 expect(chart.value).toBeTruthy() }) it('sets chart option', () => { const { setOption } = useECharts(chartRef) const option = { series: [{ type: 'pie', data: [{ name: '测试', value: 100 }], }], } setOption(option) // 验证 setOption 被调用 expect(chart.value?.setOption).toHaveBeenCalled() }) it('shows loading', () => { const { showLoading, loading } = useECharts(chartRef) showLoading({ text: '加载中...' }) expect(loading.value).toBe(true) expect(chart.value?.showLoading).toHaveBeenCalled() }) it('hides loading', () => { const { hideLoading, loading } = useECharts(chartRef) hideLoading() expect(loading.value).toBe(false) expect(chart.value?.hideLoading).toHaveBeenCalled() }) it('resizes chart', () => { const { resize } = useECharts(chartRef) resize() expect(chart.value?.resize).toHaveBeenCalled() }) it('disposes chart', () => { const { dispose, chart } = useECharts(chartRef) dispose() expect(chart.value?.dispose).toHaveBeenCalled() }) it('clears chart', () => { const { clear } = useECharts(chartRef) clear() expect(chart.value?.clear).toHaveBeenCalled() }) it('binds event', () => { const { on } = useECharts(chartRef) const handler = vi.fn() on('click', handler) expect(chart.value?.on).toHaveBeenCalledWith('click', handler) }) it('unbinds event', () => { const { off } = useECharts(chartRef) const handler = vi.fn() off('click', handler) expect(chart.value?.off).toHaveBeenCalledWith('click', handler) }) it('gets data URL', () => { const { getDataURL } = useECharts(chartRef) getDataURL({ type: 'png', pixelRatio: 2 }) expect(chart.value?.getDataURL).toHaveBeenCalledWith({ type: 'png', pixelRatio: 2, backgroundColor: '#fff', }) }) it('returns chart instance', () => { const { getInstance } = useECharts(chartRef) const instance = getInstance() expect(instance).toBeTruthy() }) })