App.test.tsx 8.34 KB
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { App } from './App';
import { getAgentList } from './api/agent';

vi.mock('./api/agent', () => ({
  getAgentList: vi.fn(),
  getAgentDetail: vi.fn(),
  deleteAgent: vi.fn(),
  updateAgentStatus: vi.fn(),
  createAgent: vi.fn(),
  updateAgent: vi.fn(),
  getEmployeeMounts: vi.fn(() => Promise.resolve({ employee_count: 0, employees: [] })),
}));

const loginStorageKey = 'agent-admin-local-login';

function renderApp(path: string) {
  return render(
    <MemoryRouter initialEntries={[path]}>
      <App />
    </MemoryRouter>,
  );
}

function getLoginInput(name: 'username' | 'password') {
  const input = document.querySelector<HTMLInputElement>(`input[name="${name}"]`);
  if (!input) {
    throw new Error(`Login input ${name} was not found`);
  }
  return input;
}

describe('App foundation', () => {
  beforeEach(() => {
    window.localStorage.clear();
    vi.clearAllMocks();
  });

  it('renders the root layout for the React application', async () => {
    renderApp('/components');

    await waitFor(() => {
      expect(screen.getByRole('main')).toBeInTheDocument();
    });
    expect(screen.getByText('Agent Admin Web')).toBeInTheDocument();
  });

  it('renders the independent component demo route', async () => {
    renderApp('/components');

    await waitFor(() => {
      expect(screen.getByRole('heading', { name: '组件库 Demo' })).toBeInTheDocument();
    });
    expect(screen.getByText('TDesign 基础控件与全局业务组合组件展示入口')).toBeInTheDocument();
    expect(screen.queryByRole('heading', { name: 'Agent管理' })).not.toBeInTheDocument();
    expect(screen.queryByRole('button', { name: '退出登录' })).not.toBeInTheDocument();
  });
});

describe('Admin login and protected routes', () => {
  beforeEach(() => {
    window.localStorage.clear();
    vi.clearAllMocks();
    vi.mocked(getAgentList).mockRejectedValue(new Error('Network error'));
  });

  it('redirects anonymous users to login and returns to the requested protected route after login', async () => {
    renderApp('/agents');

    expect(screen.getByRole('heading', { name: '岗位Agent管理后台' })).toBeInTheDocument();
    expect(screen.getByText('使用一期固定管理员账号进入本地管理后台')).toBeInTheDocument();
    expect(getLoginInput('username')).toBeInTheDocument();
    expect(getLoginInput('password')).toBeInTheDocument();
    expect(getLoginInput('username')).toHaveAttribute('placeholder', '请输入账号');
    expect(getLoginInput('password')).toHaveAttribute('placeholder', '请输入密码');
    expect(screen.queryByText('账号')).not.toBeInTheDocument();
    expect(screen.queryByText('密码')).not.toBeInTheDocument();
    expect(screen.getByRole('button', { name: '显示密码' })).toBeInTheDocument();

    fireEvent.change(getLoginInput('username'), { target: { value: 'admin' } });
    fireEvent.change(getLoginInput('password'), { target: { value: '123456' } });
    fireEvent.click(screen.getByRole('button', { name: '登录' }));

    expect(window.localStorage.getItem(loginStorageKey)).toBe('true');
    await waitFor(() => {
      expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument();
    });
    await waitFor(() => {
      expect(screen.getByText('请求失败')).toBeInTheDocument();
    });
    expect(screen.getByText('岗位Agent管理后台')).toBeInTheDocument();
    expect(screen.getByLabelText('管理员头像')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: '退出登录' })).toBeInTheDocument();
  });

  it('shows validation and credential errors without marking the user as logged in', () => {
    renderApp('/login');

    fireEvent.click(screen.getByRole('button', { name: '登录' }));

    expect(screen.getByText('请输入账号')).toBeInTheDocument();
    expect(screen.getByText('请输入密码')).toBeInTheDocument();
    expect(window.localStorage.getItem(loginStorageKey)).toBeNull();

    fireEvent.change(getLoginInput('username'), { target: { value: 'admin' } });
    fireEvent.change(getLoginInput('password'), { target: { value: 'wrong' } });
    fireEvent.click(screen.getByRole('button', { name: '登录' }));

    expect(screen.getByText('账号或密码错误')).toBeInTheDocument();
    expect(window.localStorage.getItem(loginStorageKey)).toBeNull();
  });

  it('toggles password visibility from the login password field', () => {
    renderApp('/login');

    const passwordInput = getLoginInput('password');

    expect(passwordInput.type).toBe('password');

    fireEvent.click(screen.getByRole('button', { name: '显示密码' }));

    expect(passwordInput.type).toBe('text');
    expect(screen.getByRole('button', { name: '隐藏密码' })).toBeInTheDocument();
  });

  it('keeps logged-in users on refresh and clears local state on logout', async () => {
    window.localStorage.setItem(loginStorageKey, 'true');
    vi.mocked(getAgentList).mockResolvedValue({ list: [], total: 0, page: 1, page_size: 10 });

    renderApp('/agents');

    await waitFor(() => {
      expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument();
    });

    fireEvent.click(screen.getByRole('button', { name: '退出登录' }));

    expect(screen.getByText('确认退出登录?').closest('.t-dialog')).toBeInTheDocument();
    expect(window.localStorage.getItem(loginStorageKey)).toBe('true');

    fireEvent.click(screen.getByRole('button', { name: '取消' }));

    await waitFor(() => {
      expect(screen.queryByText('确认退出登录?')).not.toBeInTheDocument();
    });
    expect(window.localStorage.getItem(loginStorageKey)).toBe('true');

    fireEvent.click(screen.getByRole('button', { name: '退出登录' }));
    fireEvent.click(screen.getByRole('button', { name: '确定' }));

    expect(window.localStorage.getItem(loginStorageKey)).toBeNull();
    expect(screen.getByRole('heading', { name: '岗位Agent管理后台' })).toBeInTheDocument();
  });

  it('renders hierarchical admin navigation with the child route selected', async () => {
    window.localStorage.setItem(loginStorageKey, 'true');
    vi.mocked(getAgentList).mockResolvedValue({ list: [], total: 0, page: 1, page_size: 10 });

    renderApp('/agents');

    await waitFor(() => {
      expect(screen.getByLabelText('左侧导航')).toBeInTheDocument();
    });
    const leftNavigation = screen.getByLabelText('左侧导航');
    expect(leftNavigation.querySelector('.t-icon-robot')).toBeInTheDocument();
    expect(leftNavigation.querySelector('.t-icon-usergroup')).toBeInTheDocument();
    expect(leftNavigation.querySelector('.t-icon-setting')).toBeInTheDocument();
    expect(within(leftNavigation).getByText('Agent列表').closest('li')).toHaveClass('t-is-active');

    fireEvent.click(screen.getByRole('button', { name: '收起菜单' }));

    expect(screen.getByRole('button', { name: '展开菜单' })).toBeInTheDocument();
    expect(screen.getByLabelText('左侧导航')).toHaveStyle({ width: '64px' });
    expect(leftNavigation.querySelector('.t-icon-robot')).toBeInTheDocument();
  });

  it('renders the skill route inside the admin shell navigation', async () => {
    window.localStorage.setItem(loginStorageKey, 'true');
    vi.mocked(getAgentList).mockResolvedValue({ list: [], total: 0, page: 1, page_size: 10 });

    renderApp('/skills');

    await waitFor(() => {
      expect(screen.getByRole('heading', { name: 'Skill目录' })).toBeInTheDocument();
    });
    expect(within(screen.getByLabelText('左侧导航')).getByText('Skill目录').closest('li')).toHaveClass('t-is-active');
    expect(screen.getAllByText('Agent管理').length).toBeGreaterThan(0);
    expect(screen.getAllByText('Skill目录').length).toBeGreaterThan(0);
  });

  it('renders independent editor pages with clickable breadcrumbs back to the secondary menu', async () => {
    window.localStorage.setItem(loginStorageKey, 'true');

    renderApp('/agents/new');

    await waitFor(() => {
      expect(screen.getByRole('heading', { name: '新建Agent' })).toBeInTheDocument();
    });

    expect(screen.getByText('新增Agent')).toBeInTheDocument();

    fireEvent.click(screen.getByRole('button', { name: 'Agent列表' }));

    await waitFor(() => {
      expect(screen.getByRole('heading', { name: 'Agent管理' })).toBeInTheDocument();
    });
  });
});