import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { beforeEach, expect, it, vi } from 'vitest'; import { MonitorRulesModal, ChannelEnrollmentPrompt } from './MonitorConfiguration'; const api = vi.hoisted(() => ({ rules: vi.fn(), effective: vi.fn(), saveRule: vi.fn(), targets: vi.fn(), target: vi.fn(), })); vi.mock('./monitorApi', async (importOriginal) => ({ ...(await importOriginal()), monitorApi: api })); beforeEach(() => { vi.clearAllMocks(); api.rules.mockResolvedValue([]); api.effective.mockResolvedValue([]); }); it('leaves default thresholds empty and preserves input on actual save failure', async () => { const user = userEvent.setup(), close = vi.fn(); api.saveRule.mockRejectedValue(new Error('规则已被修改,请刷新后重试')); render(); await waitFor(() => expect(screen.getByRole('button', { name: '保存规则' })).toBeEnabled()); expect(screen.getByLabelText('5秒到达率下限(%)')).toHaveValue(null); expect(screen.getByLabelText('启用告警')).not.toBeChecked(); await user.type(screen.getByLabelText('最低成熟样本量'), '100'); await user.type(screen.getByLabelText('5秒到达率下限(%)'), '90'); await user.click(screen.getByRole('button', { name: '保存规则' })); expect(await screen.findByRole('alert')).toHaveTextContent('规则已被修改'); expect(screen.getByLabelText('最低成熟样本量')).toHaveValue(100); expect(api.saveRule).toHaveBeenCalledWith( expect.objectContaining({ version: 0, scope: {}, config: expect.objectContaining({ enabled: false, minSamples: 100, thresholds: [90, null, null] }), }), ); expect(close).not.toHaveBeenCalled(); }); it('retries enrollment against the same saved channel without creating another channel', async () => { const user = userEvent.setup(), close = vi.fn(); const channel = { id: 'saved-channel', name: '已保存通道', version: 0, enabled: false }; api.targets.mockResolvedValue([channel]); api.target.mockRejectedValueOnce(new Error('网络中断')).mockResolvedValueOnce({ success: true }); render(); await user.click(screen.getByRole('button', { name: '加入监控' })); expect(await screen.findByRole('alert')).toHaveTextContent('无需重新创建通道'); await user.click(screen.getByRole('button', { name: '加入监控' })); await waitFor(() => expect(close).toHaveBeenCalledOnce()); expect(api.target.mock.calls).toEqual([ [channel, true], [channel, true], ]); });