authFixture.ts 1.51 KB
import { test as base, Page } from '@playwright/test';
import path from 'path';

/**
 * 认证夹具类型定义
 */
type AuthFixtures = {
  /**
   * 已认证的页面(使用保存的 auth.json)
   */
  authenticatedPage: Page;
  
  /**
   * 认证文件路径
   */
  authFilePath: string;
};

/**
 * 扩展的测试对象,包含认证夹具
 */
export const test = base.extend<AuthFixtures>({
  // 默认认证文件路径
  authFilePath: async ({}, use) => {
    await use(path.join(process.cwd(), 'auth.json'));
  },
  
  // 已认证的页面
  authenticatedPage: async ({ browser, authFilePath }, use) => {
    // 创建带有认证状态的上下文
    const context = await browser.newContext({
      storageState: authFilePath,
    });
    
    const page = await context.newPage();
    
    // 使用页面
    await use(page);
    
    // 清理
    await context.close();
  },
});

/**
 * 导出 expect 以便在测试中使用
 */
export { expect } from '@playwright/test';

/**
 * 创建一个新的认证夹具,使用自定义认证文件路径
 * @param authPath 认证文件路径
 */
export function createAuthTest(authPath: string) {
  return base.extend<AuthFixtures>({
    authFilePath: async ({}, use) => {
      await use(authPath);
    },
    authenticatedPage: async ({ browser, authFilePath }, use) => {
      const context = await browser.newContext({
        storageState: authFilePath,
      });
      const page = await context.newPage();
      await use(page);
      await context.close();
    },
  });
}