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

如何用Vitest测试SvelteKit REST API?求清晰配置与最佳实践

SvelteKit REST API 单元测试指南

1. 无需手动启动服务器的测试配置方案

方案一:直接测试API Handler函数(推荐)

这种方式不需要启动服务器,直接测试+server.ts中导出的GET/POST等函数,属于单元测试范畴,高效且无需额外配置。

步骤:

  1. 调整测试用例:导入端点的handler函数,模拟RequestEvent对象完成测试

    // src/routes/issues/issues.test.ts
    import { GET } from './+server';
    import { describe, it, expect } from 'vitest';
    
    describe('/issues API', () => {
      it('GET 请求返回200状态码', async () => {
        // 模拟RequestEvent的必要属性
        const mockRequestEvent = {
          request: new Request('http://localhost/issues'),
          params: {},
          locals: {},
          platform: {},
          route: { id: '' },
          url: new URL('http://localhost/issues')
        };
    
        const response = await GET(mockRequestEvent);
        expect(response.status).toBe(200);
    
        // 可选:验证返回数据结构
        const responseData = await response.json();
        expect(responseData).toHaveProperty('data');
      });
    });
    
  2. 更新Vite配置:指定测试环境为node(适配服务端代码测试)

    // vite.config.ts
    import { defineConfig } from 'vite';
    import { sveltekit } from '@sveltejs/kit/vite';
    
    export default defineConfig({
      plugins: [sveltekit()],
      test: {
        include: ['src/**/*.{test,spec}.{js,ts}'],
        environment: 'node',
        globals: true, // 可选:无需每次导入describe/it/expect
      },
    });
    

方案二:自动启动测试服务器(集成测试)

如果需要测试完整的路由匹配、中间件流程,可以让Vitest自动启动SvelteKit服务器:

  1. 添加服务器启停逻辑:在测试文件中使用SvelteKit的preview命令

    // src/routes/issues/issues.test.ts
    import { describe, it, expect, beforeAll, afterAll } from 'vitest';
    import { preview } from '@sveltejs/kit/vite';
    import type { PreviewServer } from 'vite';
    
    let server: PreviewServer;
    let baseUrl: string;
    
    beforeAll(async () => {
      server = await preview({
        preview: { port: 3000 }
      });
      baseUrl = 'http://localhost:3000';
    });
    
    afterAll(async () => {
      await server.httpServer.close();
    });
    
    describe('/issues API', () => {
      it('GET 请求返回200', async () => {
        const response = await fetch(`${baseUrl}/issues`);
        expect(response.status).toBe(200);
      });
    });
    
  2. Vite配置无需额外修改:依赖SvelteKit的preview服务即可运行。

2. 测试文件目录结构最佳实践

将.test.ts文件与路由端点(+server.ts)放在同一目录是推荐的实践,原因如下:

  • 就近维护:修改API逻辑后,可直接在同一目录下调整测试用例,减少目录切换成本
  • 结构清晰:目录层级与API路由一一对应,便于快速定位测试文件
  • 符合SvelteKit设计理念:遵循框架的"colocation"(就近放置)原则,和组件测试文件的放置逻辑保持一致

如果团队偏好集中管理测试文件,也可以将测试放在src/tests/api目录下,按路由结构镜像组织(比如src/tests/api/issues.test.ts),但需要手动同步目录结构,灵活性稍差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:42:28