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

使用Vitest测试SvelteKit API时如何在服务端Mock组件?

SvelteKit + Vitest:Mock服务端单例以支持HTTP测试

我正在开发一个SvelteKit应用,并尝试使用Vitest进行测试。我想要测试一个简单的API端点:

// src/routes/api/test/+server.ts

import { testService } from '$lib/server/testService';

export const POST: RequestHandler = async (requestEvent) => {
  return text(testService.sayHello());
};

我的后端服务是无状态单例:

// src/lib/server/testService.ts

class TestService {
  public sayHello() {
    return 'Hello';
  }
}

export const testService = new TestService();

使用Vitest测试时:

  • 直接测试服务运行正常:
import { testService } from '$lib/server/testService';
//...

test('test service', async () => {
  const result = testService.sayHello();
  assert.equal(result, 'Hello');
});
  • Mock服务的sayHello方法并本地调用也能正常工作:
import { testService } from '$lib/server/testService';
//...

test('test mocked service', async () => {
  const sayHelloSpy = vi.spyOn(testService, 'sayHello');
  sayHelloSpy.mockImplementation(() => 'mocked!');

  const result = testService.sayHello();
  assert.equal(result, 'mocked!');

  sayHelloSpy.mockRestore();
});
  • 但无法Mock服务让HTTP fetch调用使用Mock版本:
import { testService } from '$lib/server/testService';
//...

test('test mocked service with fetch', async () => {
  const sayHelloSpy = vi.spyOn(testService, 'sayHello');
  sayHelloSpy.mockImplementation(() => 'mocked!');

  const response = await fetch(`http://localhost:12323/api/test`, {
    method: 'POST',
    headers: {
      'content-type': 'application/json'
    }
  });
  assert.isTrue(response.ok);

  const result = await response.text();
  assert.equal(result, 'mocked!'); // *失败!结果始终是"Hello"而非"mocked!"*

  sayHelloSpy.mockRestore();
});

我使用VS Code的如下启动配置调试这些测试:

{
  "name": "Vitest - current file",
  "type": "node",
  "request": "launch",
  "program": "${workspaceRoot}/node_modules/vitest/vitest.mjs",
  "args": [
    "run",
    "--run",
    "--test-timeout=0",
    "--api",
    "12323",
    "${fileDirname}/${fileBasenameNoExtension}.ts"
  ],
  "env": {
    "NODE_ENV": "tests"
  },
  "skipFiles": ["<node_internals>/**", "**/node_modules/**"],
  "sourceMaps": true,
  "smartStep": true,
  "timeout": 10000,
  "autoAttachChildProcesses": true,
  "internalConsoleOptions": "neverOpen",
  "console": "integratedTerminal",
  "outputCapture": "std",
  "protocol": "inspector"
}

我对Vitest能轻松搭建服务器进行HTTP调用测试印象深刻,但我希望能够Mock服务端上下文内的一些对象,请问这是否可行?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 04:52:02