You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright+Angular图片上传测试失败:文件路径错误求助

解决Playwright测试Angular图片上传时的文件找不到问题

你遇到的ENOENT错误本质是路径解析错误——Playwright运行时的工作目录和你预期的不一致,导致它找不到指定路径下的文件。以下是具体解决方法:

1. 使用基于测试文件的绝对路径(最可靠)

利用Node.js的path模块,结合当前测试文件的位置(__dirname)来构建正确的文件路径,避免工作目录差异带来的问题。

示例代码:

import { test, expect } from '@playwright/test';
import path from 'path';

test('图片上传测试', async ({ page }) => {
  // 构建绝对路径:根据你的spec.ts位置调整路径层级
  // 假设spec.ts在e2e/src下,那么../就能回到e2e目录,再指向fixtures
  const testImagePath = path.resolve(__dirname, '../fixtures/test-image.jpg');

  // 方法一:直接给input元素设置文件(适用于不触发弹窗的上传)
  await page.locator('input[type="file"]').setInputFiles(testImagePath);

  // 方法二:处理弹窗式上传(点击按钮后弹出文件选择框)
  const [fileChooser] = await Promise.all([
    page.waitForEvent('filechooser'),
    page.locator('#upload-trigger-btn').click() // 替换成你的上传触发按钮选择器
  ]);
  await fileChooser.setFiles(testImagePath);

  // 验证上传成功(替换成你的验证逻辑)
  await expect(page.locator('.upload-success-indicator')).toBeVisible();
});

2. 检查Playwright配置的测试目录

确认playwright.config.ts中的testDir是否指向你的e2e目录,这会影响相对路径的解析:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: './e2e', // 确保这里指向你的e2e目录
  // 其他配置项...
});

3. 核对路径细节

  • 检查文件名/目录名的拼写,包括大小写(Windows系统虽不区分,但拼写错误依然会导致找不到文件)
  • 在终端进入e2e目录,执行dir fixtures/test-image.jpg(Windows)或ls fixtures/test-image.jpg(Mac/Linux),确认文件确实存在

内容的提问来源于stack exchange,提问作者LaCodeM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 23:22:12