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

如何在Playwright组件测试中导入函数?(Svelte/SvelteKit项目)

解决SvelteKit中Playwright组件测试共享模拟函数的问题

1. 独立组织共享模拟函数

不要把模拟函数放在Svelte组件的context="module"中,直接在测试目录下创建独立的工具模块。比如在项目根目录新建tests/utils/mock-data.js(TypeScript项目用.ts):

// 生成模拟用户数据的共享函数
export function getMockUser() {
  return {
    id: '123',
    name: '测试用户',
    email: 'test@example.com'
  };
}

// 生成模拟商品列表的函数
export function getMockProducts(count = 3) {
  return Array.from({ length: count }, (_, i) => ({
    id: `prod-${i+1}`,
    name: `商品${i+1}`,
    price: (i+1)*10
  }));
}

2. 确认Playwright配置与模块解析

确保playwright.config.js(或.ts)的测试目录配置正确,无需额外特殊配置,但TypeScript项目要保证tsconfig.json包含测试目录:

Playwright配置示例(关键部分)

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

export default defineConfig({
  testDir: './tests/components', // 你的组件测试文件存放目录
  // 其他配置(比如浏览器、报告等)保持默认即可
});

TypeScript配置补充

在tsconfig.json的include数组中添加测试目录,确保TS能解析测试文件的导入:

{
  "include": [
    "src/**/*",
    "tests/**/*"
  ]
}

3. 在测试文件中直接导入使用

以tests/components/UserProfile.test.js为例,直接通过相对路径导入共享函数:

import { test, expect } from '@playwright/experimental-ct-svelte';
import UserProfile from '$lib/components/UserProfile.svelte';
import { getMockUser } from '../utils/mock-data'; // 注意相对路径对应文件位置

test('UserProfile组件正确渲染模拟用户数据', async ({ mount }) => {
  const mockUser = getMockUser();
  const component = await mount(UserProfile, {
    props: {
      user: mockUser
    }
  });
  
  await expect(component.locator('h2')).toContainText(mockUser.name);
  await expect(component.locator('.user-email')).toHaveText(mockUser.email);
});

4. 常见问题排查

  • 若导入失败,先检查文件相对路径是否正确,避免使用SvelteKit的路径别名(如$lib),测试环境下优先用相对路径
  • 确认共享函数文件的导出语法正确,必须用export暴露需要复用的函数
  • 若存在缓存问题,可重启Playwright测试服务或清除项目依赖缓存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:35:48