跳至主要内容

创建模拟对象以抽象层

Copilot Chat 可帮助创建可用于单元测试的模拟对象。

在编写单元测试时,确保测试是隔离的、且不依赖外部服务非常重要。实现这一目标的一种方法是创建抽象应用各层的模拟对象。Copilot Chat 可以帮助你生成创建这些模拟对象所需的代码。

示例情景

想象一个使用 TypeScript 构建的网站,展示跑步者列表。你有一个从数据库中获取跑步者的服务,以及使用该服务的服务器端代码。你希望测试服务器端代码,但不想真的调用数据库。你可以让 Copilot Chat 为该服务生成一个模拟对象。

// SvelteKit example at +page.server.ts
import service from './service';

export async function load({ params }) {
  const runner = await service.getRunner(params.id);

  return {
    runner
  };
}

示例提示

此示例假设你使用 vitest 进行测试,但同样适用于其他测试运行器。

Copilot 提示
/tests Create a unit test to ensure the service is called correctly. Mock the service object.

如果你已有现有测试希望 Copilot 用作模型,可以使用 #file: path/to/test-file.js 提供文件路径,并在提示中包含该信息。

示例回复

注意

以下响应为示例。Copilot Chat 的回复具有不确定性,您可能会得到与此处显示的不同的响应。

Copilot 会提供它将实现的计划以及包含模拟对象的代码文本。

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { load } from './+page.server.ts';

// Mock the entire service module
vi.mock('./service', () => ({
  default: {
    getRunner: vi.fn()
  }
}));

// Import the mocked service
import service from './service';

describe('load function', () => {
  const mockRunner = {
    id: '123',
    name: 'Test Runner',
    status: 'active'
  };

  beforeEach(() => {
    // Reset mock before each test
    vi.resetAllMocks();

    // Setup default mock implementation
    (service.getRunner as any).mockResolvedValue(mockRunner);
  });

  it('should fetch runner with correct id', async () => {
    const params = { id: '123' };
    const result = await load({ params });

    expect(service.getRunner).toHaveBeenCalledWith('123');
    expect(service.getRunner).toHaveBeenCalledTimes(1);
    expect(result).toEqual({ runner: mockRunner });
  });
});

延伸阅读

© . This site is unofficial and not affiliated with GitHub, Inc.