跳到主要内容

Web 服务器

简介

Playwright 在配置文件中提供了 webserver 选项,使您能够在运行测试前启动本地开发服务器。这在开发期间编写测试时非常有用,特别是当您没有可用于测试的预发布或生产环境 URL 时。

配置 Web 服务器

在 Playwright 配置中使用 webserver 属性可以在测试期间启动开发 Web 服务器。

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
// 在开始测试前运行本地开发服务器
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
stdout: 'ignore',
stderr: 'pipe',
},
});
属性描述
testConfig.webServer在测试期间启动开发 Web 服务器(或多个服务器)。
command启动应用本地开发服务器的 shell 命令。
cwd生成进程的当前工作目录,默认为配置文件所在目录。
env为命令设置的环境变量,默认为 process.env
gracefulShutdown如何关闭进程。如果未指定,则强制使用 SIGKILL 终止进程组。如果设置为 { signal: 'SIGTERM', timeout: 500 },则向进程组发送 SIGTERM 信号,如果 500ms 内未退出则发送 SIGKILL。也可以使用 SIGINT 作为信号。0 超时表示不会发送 SIGKILL。Windows 不支持 SIGTERMSIGINT 信号,因此在 Windows 上此选项会被忽略。注意关闭 Docker 容器需要使用 SIGTERM
ignoreHTTPSErrors获取 url 时是否忽略 HTTPS 错误。默认为 false
name指定 Web 服务器的自定义名称。此名称将作为日志消息的前缀。默认为 [WebServer]
reuseExistingServer如果为 true,当 url 上有现有服务器时会复用。如果该 url 上没有运行服务器,则会运行命令启动新服务器。如果为 false,当 url 上有现有进程监听时会抛出错误。要查看 stdout,可以设置 DEBUG=pw:webserver 环境变量。
stderr是否将命令的 stderr 输出到进程 stderr 或忽略它。默认为 "pipe"
stdout如果为 "pipe",则将命令的 stdout 输出到进程 stdout。如果为 "ignore",则忽略命令的 stdout。默认为 "ignore"
timeout等待进程启动并可用多长时间(毫秒)。默认为 60000。
urlHTTP 服务器的 URL,当服务器准备接受连接时预期返回 2xx、3xx、400、401、402 或 403 状态码。

添加服务器超时设置

Web 服务器有时可能需要更长时间才能启动。在这种情况下,你可以增加等待服务器启动的超时时间。

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
// 其余配置...

// 在开始测试前运行本地开发服务器
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000,
},
});

添加 baseURL

我们还建议在配置文件的 use: {} 部分指定 baseURL,这样测试就可以使用相对 URL,而不必反复指定完整 URL。

当使用 page.goto()page.route()page.waitForURL()page.waitForRequest()page.waitForResponse() 时,会通过 URL() 构造函数来构建对应的 URL。例如,将 baseURL 设置为 http://localhost:3000 并在测试中导航到 /login,Playwright 会使用 http://localhost:3000/login 来运行测试。

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
// 其他配置...

// 在开始测试前运行本地开发服务器
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
use: {
baseURL: 'http://localhost:3000',
},
});

现在你可以在页面导航时使用相对路径:

test.spec.ts
import { test } from '@playwright/test';

test('test', async ({ page }) => {
// 这将导航到 http://localhost:3000/login
await page.goto('./login');
});

多 Web 服务器

可以通过提供 webServer 配置数组来同时启动多个 Web 服务器(或后台进程)。更多信息请参阅 testConfig.webServer

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
webServer: [
{
command: 'npm run start',
url: 'http://localhost:3000',
name: '前端服务',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
{
command: 'npm run backend',
url: 'http://localhost:3333',
name: '后端服务',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
}
],
use: {
baseURL: 'http://localhost:3000',
},
});