run-e2e.mjs 2.41 KB
import { existsSync, readFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process';

const envName = process.argv[2];
const rawArgs = process.argv.slice(3);
const appProjects = new Map([
  ['dj-carlife-web', {
    root: 'projects/dj-carlife-web',
    suites: new Map([
      ['basic', 'projects/dj-carlife-web/tests/basic'],
      ['saas-v5.8.6', 'projects/dj-carlife-web/tests/saas-v5.8.6'],
    ]),
  }],
]);
let suiteName = 'all';
let appProjectName = 'dj-carlife-web';
const extraArgs = [];

for (let index = 0; index < rawArgs.length; index += 1) {
  const arg = rawArgs[index];
  if (arg === '--app-project') {
    appProjectName = rawArgs[index + 1] || '';
    index += 1;
    continue;
  }
  if (arg.startsWith('--app-project=')) {
    appProjectName = arg.split('=').slice(1).join('=');
    continue;
  }
  if (arg === '--suite') {
    suiteName = rawArgs[index + 1] || '';
    index += 1;
    continue;
  }
  if (arg.startsWith('--suite=')) {
    suiteName = arg.split('=').slice(1).join('=');
    continue;
  }
  extraArgs.push(arg);
}

if (!appProjects.has(appProjectName)) {
  console.error('未知测试项目:' + appProjectName + '。可用项目:' + [...appProjects.keys()].join('、') + '。');
  process.exit(1);
}

const appProject = appProjects.get(appProjectName);
const suitePath = appProject.suites.get(suiteName);
if (suiteName !== 'all' && !suitePath) {
  console.error('未知用例范围:' + suiteName + '。请确认该项目已配置此用例范围。');
  process.exit(1);
}

const hasProjectArg = extraArgs.some((arg) => arg === '--project' || arg.startsWith('--project='));
const playwrightArgs = [
  'playwright',
  'test',
  ...(hasProjectArg ? [] : ['--project=edge']),
  ...(suitePath ? [suitePath] : [appProject.root]),
  ...extraArgs,
];
if (existsSync('.env.local')) {
  const lines = readFileSync('.env.local', 'utf8').split(/\r?\n/);
  for (const line of lines) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#') || !trimmed.includes('=')) continue;

    const [key, ...valueParts] = trimmed.split('=');
    process.env[key.trim()] = valueParts.join('=').trim();
  }
}

const result = spawnSync('npx', playwrightArgs, {
  stdio: 'inherit',
  shell: true,
  env: {
    ...process.env,
    ...(envName ? { E2E_ENV: envName } : {}),
    E2E_APP_PROJECT: appProjectName,
  },
});

if (result.error) {
  console.error(result.error.message);
}

process.exit(result.status ?? 1);