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

使用NestJS Throttler单元测试时依赖注入失败问题求助

解决NestJS Throttler单元测试依赖注入错误

你遇到的错误是因为测试模块上下文缺少MyThrottlerGuard所需的THROTTLER:MODULE_OPTIONS依赖,以下是两种可行的解决方法:

方法一:导入ThrottlerModule并配置测试选项

直接在测试模块中导入带配置的ThrottlerModule,让Nest自动提供所需的依赖:

import { Test } from '@nestjs/testing';
import { ThrottlerModule } from '@nestjs/throttler';
import { MyThrottlerGuard } from './my-throttler.guard';
import { Reflector } from '@nestjs/core';

describe('MyThrottlerGuard', () => {
  let guard: MyThrottlerGuard;

  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [
        ThrottlerModule.forRoot({
          ttl: 60,
          limit: 10,
        }),
      ],
      providers: [MyThrottlerGuard, Reflector],
    }).compile();

    guard = moduleRef.get<MyThrottlerGuard>(MyThrottlerGuard);
  });

  it('should be defined', () => {
    expect(guard).toBeDefined();
  });
});

方法二:手动Mock依赖

如果不需要真实的Throttler配置和存储实现,可以手动mock所有依赖项:

import { Test } from '@nestjs/testing';
import { MyThrottlerGuard } from './my-throttler.guard';
import { Reflector } from '@nestjs/core';
import { THROTTLER_MODULE_OPTIONS, ThrottlerStorage } from '@nestjs/throttler';

describe('MyThrottlerGuard', () => {
  let guard: MyThrottlerGuard;

  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      providers: [
        MyThrottlerGuard,
        Reflector,
        {
          provide: THROTTLER_MODULE_OPTIONS,
          useValue: { ttl: 60, limit: 10 },
        },
        {
          provide: ThrottlerStorage,
          useValue: {
            increment: jest.fn().mockResolvedValue({ totalHits: 1 }),
            decrement: jest.fn(),
            resetKey: jest.fn(),
          },
        },
      ],
    }).compile();

    guard = moduleRef.get<MyThrottlerGuard>(MyThrottlerGuard);
  });

  it('should be defined', () => {
    expect(guard).toBeDefined();
  });
});

关键说明

  • THROTTLER:MODULE_OPTIONS是ThrottlerModule提供的配置token,必须在测试模块中通过导入模块或手动提供的方式暴露
  • Reflector是Nest核心服务,需要显式添加到测试模块的providers中
  • 如果你的自定义守卫还依赖其他服务,需要同步在测试模块中添加对应的提供者或mock实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:45:07