端到端测试工具

Playwright是一个用于端到端测试的工具,支持多浏览器自动化测试和交互式UI模式,适用于Web应用的自动化测试和调试。

  • by kanakverma89
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 kanakverma89/playwright-e2e-tests

使用说明

剧作家E2E测试

使用Playwright设置和运行端到端测试的说明和注意事项。


📦 安装

1.✅安装剧作家

npm init playwright@latest

2.✅验证安装

npx playwright --help

⌨️ 键盘快捷键

快捷方式 操作
Ctrl + 开放式终端

🚀 可用命令

从项目目录运行以下命令:

基本测试执行

npx playwright test

在非无头模式下运行测试

 npx playwright test --headed

运行所有端到端测试。

交互式UI模式

npx playwright test --ui

启动交互式UI模式进行测试。

在特定浏览器上运行测试

npx playwright test --project=chromium

仅在桌面Chrome上运行测试。

运行特定测试文件

npx playwright test example

在特定文件中运行测试。

调试模式

npx playwright test --debug

在调试模式下运行测试以进行故障排除。

自动生成测试

npx playwright codegen

使用Codegen工具自动生成测试代码。


📋 命名规范

遵循以下命名约定,以保持整个项目的一致性和可读性:

文件夹和文件

类型 惯例 示例
测试文件 kebab-case.spec.ts login.spec.ts, user-profile.spec.ts
页面对象文件 kebab-case.page.ts login.page.ts, dashboard.page.ts
帮助程序/实用程序文件 kebab-case.helper.ts common.helper.ts, api-client.helper.ts
文件夹名称 kebab-case pages/, helpers/, fixtures/

页面对象类

// Use PascalCase for class names
export class LoginPage {
  // Page object implementation
}

export class DashboardPage {
  // Page object implementation
}

规范文件

// Use descriptive test names
describe('Login Feature', () => {
  test('should login successfully with valid credentials', async () => {
    // Test implementation
  });

  test('should display error message with invalid credentials', async () => {
    // Test implementation
  });
});

变量和参数

// Use camelCase for variables and parameters
let userName = 'John Doe';
const userEmail = 'john@example.com';
let isLoggedIn = true;

// In functions
async function navigateToLoginPage(pageObject: LoginPage) {
  // Function implementation
}

常量

// Use UPPER_SNAKE_CASE for constants
const BASE_URL = 'https://example.com';
const LOGIN_PAGE_TIMEOUT = 30000;
const MAX_RETRY_ATTEMPTS = 3;
const DEFAULT_WAIT_TIME = 5000;

选择器和定位器

// Use descriptive names, camelCase
const loginButton = page.locator('[data-test="login-btn"]');
const emailInput = page.locator('#email');
const usernameField = page.locator('input[name="username"]');

📁 框架文件夹结构

PLAYWRIGHT-E2E-TESTS/
│
├── .github/                          # CI/CD configuration folder
│
├── .vscode/                          # Editor-specific settings
│   └── mcp.json                      # MCP server config for VS Code
│
├── config/                           # Environment-specific config files
│
├── data/                             # Static data and constants
│   └── constants.json                # Common constants used in tests
│
├── debug/                            # Optional: Debug-related outputs/logs
│
├── logs/                             # Application/test logs
│
├── node_modules/                     # Auto-generated dependencies
│
├── playwright-report/                # Playwright HTML test report output
│
├── test-results/                     # Test execution artifacts
│
├── resources/                        # Misc test resources (images, files, etc.)
│
├── tests/                            # All organized test files
│   ├── api/                          # API test specs
│   ├── demo/                         # Demo-related test specs
│   ├── devices/                      # Device related scenarios
│   ├── e2e/                          # End-to-end test specs
│   ├── functional/                   # Functional test cases
│   ├── helpers/                      # Utility functions for tests
│   └── page-objects/                 # Page Object Model files
│
├── tests-examples/                   # Auto-generated sample test scenarios
│
├── .env.example                      # Template for environment variables
│
├── .gitignore                        # Git ignored files and folders
│
├── package-lock.json                 # Dependency lock file
│
├── package.json                      # Project metadata and scripts
│
├── playwright.config.ts              # Playwright configuration
│
└── README.md                         # Project documentation

文件夹描述

文件夹 用途
.github/ 包含CI/CD工作流配置和GitHub操作
.vscode/ VS代码工作区设置和扩展配置
config/ 特定于环境的配置文件(开发、暂存、生产)
data/ 静态测试数据、常数和夹具
debug/ 调试日志和临时调试输出
logs/ 应用程序和测试执行日志
playwright-report/ 测试执行后生成的HTML测试报告
test-results/ 测试工件,包括屏幕截图和视频
resources/ 测试资源,如图像、文件和模拟数据
tests/api/ API测试规范
tests/demo/ 演示和概念验证测试场景
tests/devices/ 设备特定和响应式测试场景
tests/e2e/ 端到端用户工作流测试
tests/functional/ 功能组件和特性测试
tests/helpers/ 可重用的实用函数和辅助方法
tests/page-objects/ UI元素的页面对象模型类
tests-examples/ 从Playwright init自动生成示例测试

🔧 推荐的VS代码扩展

建议使用以下扩展来增强您的开发体验:

扩展 目的 出版商
VS代码图标 文件和文件夹图标,以实现更好的视觉组织 VSCode图标团队
Prettier-代码格式化工具 自动代码格式化以保持一致的风格 预处理
路径智能感知 文件路径和导入的自动完成 Christian Kohler
npm智能感知 npm模块和包的自动完成 Christian Kohler
JavaScript(ES6)代码段 JavaScript/TypeScript的有用代码片段 charalampos karypidis
gitignore发生器 为您的项目生成.gitignore文件 Michealmikeyy

安装说明

您可以直接在VS Code中安装这些扩展:

  1. 打开“扩展”视图(Ctrl + Shift + X 在Windows/Linux或 Cmd + Shift + X 在Mac上)
  2. 按名称搜索每个扩展名
  3. 点击 安装 在扩展卡上

或者通过命令行安装:

code --install-extension vscode-icons-team.vscode-icons
code --install-extension esbenp.prettier-vscode
code --install-extension christian-kohler.path-intellisense
code --install-extension christian-kohler.npm-intellisense
code --install-extension xabikos.JavaScriptSnippets
code --install-extension michealmikeyy.gitignore-generator

扩展详细信息

🎨 VS代码图标

  • 为文件和文件夹添加彩色图标
  • 使文件导航更容易、更快
  • 支持Playwright和TypeScript文件

✨ Prettier-代码格式化工具

  • 保存时自动格式化代码
  • 在整个项目中保持一致的代码风格
  • 在中配置 .prettierrc 或 package.json

📁 路径智能感知

  • 键入时自动完成文件路径
  • 适用于导入和文件引用
  • 支持所有文件类型

📦 npm智能感知

  • 自动完成npm包名称
  • 显示软件包版本
  • 非常适合管理依赖关系

💻 JavaScript(ES6)代码段

  • 为常见模式提供快速代码片段
  • 使用模板加快开发速度
  • 包括箭头函数、async/await等

🙈 gitignore发生器

  • 轻松生成 .gitignore 项目的文件
  • 支持多种语言和框架
  • 命令: gitignore: Generate

� Git命令和工作流

管理Playwright E2E测试项目的基本Git命令:

初始设置

# Initialize a new Git repository
git init

# Clone an existing repository
git clone <repository-url>

# Configure your Git identity (one-time setup)
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# Verify your configuration
git config --list

查看状态和历史记录

# Check status of working directory
git status

# View commit history
git log

# View commit history with graph (one-line format)
git log --oneline --graph --all

# View changes in working directory
git diff

# View changes staged for commit
git diff --staged

# View specific file history
git log -- <file-path>

与分支机构合作

# Create a new branch
git branch <branch-name>

# Create and switch to a new branch
git checkout -b <branch-name>

# Switch to an existing branch
git checkout <branch-name>

# List all branches (local)
git branch

# List all branches (local and remote)
git branch -a

# Delete a branch
git branch -d <branch-name>

# Delete a branch forcefully
git branch -D <branch-name>

# Rename current branch
git branch -m <new-branch-name>

分期与提交

# Stage all changes
git add .

# Stage specific file
git add <file-path>

# Commit with message
git commit -m "Your commit message"

# Commit with detailed message
git commit -m "Title" -m "Detailed description"

# Amend last commit (add changes without new commit)
git commit --amend

# View staged changes
git diff --cached

推拉

# Push to remote repository
git push

# Push specific branch to remote
git push origin <branch-name>

# Push all branches
git push --all

# Pull latest changes from remote
git pull

# Pull from specific remote branch
git pull origin <branch-name>

# Fetch latest changes without merging
git fetch

# Fetch from all remotes
git fetch --all

合并和重新设置基础

# Merge branch into current branch
git merge <branch-name>

# Merge without fast-forward (creates merge commit)
git merge --no-ff <branch-name>

# Rebase current branch onto another branch
git rebase <branch-name>

# Continue after resolving rebase conflicts
git rebase --continue

# Abort rebase
git rebase --abort

撤消更改

# Discard changes in working directory
git checkout -- <file-path>

# Unstage changes
git reset <file-path>

# Undo last commit (keep changes)
git reset --soft HEAD~1

# Undo last commit (discard changes)
git reset --hard HEAD~1

# Revert a commit (creates new commit)
git revert <commit-hash>

停滞的变化

# Save changes temporarily
git stash

# List all stashes
git stash list

# Apply most recent stash
git stash apply

# Apply specific stash
git stash apply stash@{<index>}

# Apply and remove stash
git stash pop

# Delete specific stash
git stash drop stash@{<index>}

# Delete all stashes
git stash clear

远程仓库

# List all remote repositories
git remote -v

# Add a remote repository
git remote add <name> <url>

# Remove a remote repository
git remote remove <name>

# Rename a remote
git remote rename <old-name> <new-name>

# Change remote URL
git remote set-url <name> <new-url>

通用工作流示例

# 1. Create and switch to a new feature branch
git checkout -b feature/login-tests

# 2. Make changes to your test files
# (edit files...)

# 3. Check status
git status

# 4. Stage changes
git add tests/e2e/login.spec.ts

# 5. Commit changes
git commit -m "feat: add login functionality tests"

# 6. Push to remote
git push origin feature/login-tests

# 7. Create a pull request on GitHub/GitLab/Bitbucket

# 8. After merge, switch back to main branch
git checkout main

# 9. Pull latest changes
git pull origin main

# 10. Delete feature branch
git branch -d feature/login-tests

常用别名(可选)

将这些添加到您的 .gitconfig 要获得更快的命令:

git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual 'log --oneline --graph --all'

然后使用:

git st          # instead of git status
git co -b test  # instead of git checkout -b test
git ci -m "msg" # instead of git commit -m "msg"

�🏁 入门指南

要开始测试,请运行:

npx playwright test