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

NestJS单元测试报错:无法解析RescuerFunctionRepository依赖

解决NestJS RescuerFunctionRepository单元测试依赖解析错误

问题描述

为基于NestJS的数据库仓库RescuerFunctionRepository编写单元测试时,运行测试出现以下错误:

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

测试代码如下:

describe('RescuerFunctionRepository', () => {
  let repository: RescuerFunctionRepository

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [RescuerFunctionRepository],
    }).compile()

    repository = module.get<RescuerFunctionRepository>(RescuerFunctionRepository)
  })

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

模块结构:

  • AppModule导入CommonModule
  • CommonModule导入并导出DatabaseModule
  • DatabaseModule通过forRootAsync注册SequelizeModule,所有仓库均已注册为提供者并导出

RescuerFunctionRepository代码:

import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/sequelize'
import { CreationAttributes, Transaction, WhereOptions } from 'sequelize'
import { RescuerFunction } from '../../models/rescuer-function.model'

@Injectable()
export class RescuerFunctionRepository {
  constructor(
    @InjectModel(RescuerFunction)
    private userModel: typeof RescuerFunction
  ) {}

  find(where: WhereOptions<RescuerFunction>, trans?: Transaction): Promise<RescuerFunction | null> {
    return this.userModel.findOne({
      where: where,
      transaction: trans,
    })
  }

  insert(attributes: CreationAttributes<RescuerFunction>, trans?: Transaction): Promise<RescuerFunction> {
    return this.userModel.create(attributes, {
      transaction: trans,
    })
  }
}

解决方案

错误根源是RescuerFunctionRepository的构造函数依赖@InjectModel(RescuerFunction)注入的模型实例,但测试模块中未提供该依赖。以下是三种可行的解决方式:

1. 模拟模型依赖(推荐用于单元测试)

直接模拟仓库所需的模型实例,无需连接真实数据库:

import { getModelToken } from '@nestjs/sequelize';

describe('RescuerFunctionRepository', () => {
  let repository: RescuerFunctionRepository;
  // 模拟模型的核心方法
  const mockRescuerFunctionModel = {
    findOne: jest.fn().mockResolvedValue({ id: 1, name: 'test' }),
    create: jest.fn().mockResolvedValue({ id: 2, name: 'new' }),
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        RescuerFunctionRepository,
        {
          // 使用getModelToken获取模型的注入令牌
          provide: getModelToken(RescuerFunction),
          useValue: mockRescuerFunctionModel,
        },
      ],
    }).compile();

    repository = module.get<RescuerFunctionRepository>(RescuerFunctionRepository);
  });

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

  // 测试find方法逻辑
  it('should return a rescuer function when find is called', async () => {
    const result = await repository.find({ id: 1 });
    expect(result).toEqual({ id: 1, name: 'test' });
    expect(mockRescuerFunctionModel.findOne).toHaveBeenCalledWith({
      where: { id: 1 },
      transaction: undefined,
    });
  });
});

2. 导入已配置的数据库模块

如果需要使用真实测试数据库(如内存数据库),直接导入包含Sequelize配置的模块:

describe('RescuerFunctionRepository', () => {
  let repository: RescuerFunctionRepository;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      // 导入DatabaseModule或CommonModule,确保模块已注册RescuerFunction模型
      imports: [DatabaseModule],
    }).compile();

    repository = module.get<RescuerFunctionRepository>(RescuerFunctionRepository);
  });

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

注意:需确保测试环境的数据库配置正确(例如使用SQLite内存库),避免污染生产数据。

3. 使用Sequelize测试工具模块

利用@nestjs/sequelize/testing提供的SequelizeTestingModule简化测试配置:

import { SequelizeTestingModule } from '@nestjs/sequelize/testing';

describe('RescuerFunctionRepository', () => {
  let repository: RescuerFunctionRepository;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        // 注册测试用的模型
        SequelizeTestingModule.forFeature([RescuerFunction]),
      ],
      providers: [RescuerFunctionRepository],
    }).compile();

    repository = module.get<RescuerFunctionRepository>(RescuerFunctionRepository);
  });

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:34:59