mockBoundary.test.ts 2.49 KB
import { describe, it, expect } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const SRC_DIR = path.resolve(__dirname, '..');

// Runtime files that should NOT import from mocks/api
const RUNTIME_FILES = [
  'hooks/useHomeData.ts',
  'pages/Home/HomePage.tsx',
  'components/Banner.tsx',
  'components/PositionTabs.tsx',
  'components/AgentCard.tsx',
  'components/PositionAbilityArea.tsx',
  'components/MethodologySection.tsx',
  'components/QrcodeModal.tsx',
  'App.tsx',
  'main.tsx',
];

describe('Mock 边界测试', () => {
  describe('运行时代码不引用 mock API', () => {
    it('useHomeData 不导入 mocks/api', () => {
      const useHomeDataPath = path.join(SRC_DIR, 'hooks/useHomeData.ts');
      const content = fs.readFileSync(useHomeDataPath, 'utf-8');

      expect(content).not.toContain('from \'../mocks/api\'');
      expect(content).not.toContain('from "./mocks/api"');
      expect(content).not.toContain('from \'../../mocks/api\'');
    });

    it('所有运行时组件不导入 mocks/api', () => {
      for (const file of RUNTIME_FILES) {
        const filePath = path.join(SRC_DIR, file);
        if (fs.existsSync(filePath)) {
          const content = fs.readFileSync(filePath, 'utf-8');
          expect(content).not.toMatch(/from ['"].*mocks\/api['"]/);
        }
      }
    });

    it('运行时文件不直接使用 MOCK_FIXTURES', () => {
      for (const file of RUNTIME_FILES) {
        const filePath = path.join(SRC_DIR, file);
        if (fs.existsSync(filePath)) {
          const content = fs.readFileSync(filePath, 'utf-8');
          expect(content).not.toContain('MOCK_FIXTURES');
        }
      }
    });
  });

  describe('测试代码可以使用 mock fixture', () => {
    it('测试文件允许导入 mocks/data', () => {
      const testFile = path.join(SRC_DIR, '__tests__/mock-contract.test.ts');
      if (fs.existsSync(testFile)) {
        const content = fs.readFileSync(testFile, 'utf-8');
        // Test files are allowed to import mocks
        expect(content).toMatch(/from ['"].*mocks/);
      }
    });
  });

  describe('API 模块存在', () => {
    it('api/types.ts 存在', () => {
      expect(fs.existsSync(path.join(SRC_DIR, 'api/types.ts'))).toBe(true);
    });

    it('api/official-site.ts 存在', () => {
      expect(fs.existsSync(path.join(SRC_DIR, 'api/official-site.ts'))).toBe(true);
    });
  });
});