单元测试期间的 NestJS 依赖注入

NestJS dependency injection during unit test

在用jest进行单元测试的时候遇到了NestJS的依赖注入问题。这是我的代码库。 app.controller.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';

describe('AppController', () => {
  let appController: AppController;

  beforeEach(async () => {
    const app: TestingModule = await Test.createTestingModule({
      controllers: [AppController],
      providers: [AppService],
    }).compile();

    appController = app.get<AppController>(AppController);
  });

  describe('root', () => {
    it('should return "Hello World!"', () => {
      expect(appController.getHello()).toBe('Hello World!');
    });
  });
});

问题是,app.service.ts

中存在依赖注入
import { Injectable, CACHE_MANAGER, Inject } from "@nestjs/common";
import {Cache} from "cache-manager";

@Injectable()
export class AppService {
    constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}

    getHello(): string {
        return "Hello World!";
    }
}

一般情况下,nest 在启动时会自动执行依赖注入,但在 运行 单元测试时不会发生这种情况,并出现以下错误:

Nest can't resolve dependencies of the AppService (?). Please make sure that the argument CACHE_MANAGER at index [0] is available in the RootTestModule context.

知道如何解决这个问题吗?

您需要将 CACHE_MANAGER 作为提供程序添加到您的测试模块:

const app: TestingModule = await Test.createTestingModule({
  controllers: [AppController],
  providers: [
    AppService,
    { provide: CACHE_MANAGER, useFactory: jest.fn() },
  ],
}).compile();