使用Automock时NestJS依赖模拟返回undefined问题求助
问题:获取的依赖模拟对象返回undefined
请问有人知道为何我获取的依赖模拟对象在控制台中返回undefined吗?
示例代码如下:
example.service.spec.ts
import { TestBed } from "@automock/jest"; import { ExampleService } from "./example.service"; import { ExampleEntity } from "./example.entity"; describe('ExampleService', () => { let exampleService: ExampleService; let exampleRepository: jest.Mocked<Repository<ExampleEntity>>; beforeAll(() => { const { unit, unitRef } = TestBed.create(ExampleService).compile(); exampleService = unit; exampleRepository = unitRef.get(Repository<ExampleEntity>); console.log(exampleRepository); // --> 返回undefined }); //... })
example.service.ts
import { Repository } from "typeorm"; import { ExampleEntity } from "./example.entity"; //... @Injectable() export class ExampleService { constructor( @InjectRepository(ExampleEntity) private readonly exampleRepository: Repository<ExampleEntity> ) //... }
依赖版本:
- @nestjs: 9.0.0
- @automock/jest: 1.0.1
- @typeorm: 0.3.12
解决方案
问题出在依赖获取的方式上。因为你在ExampleService构造函数中使用了@InjectRepository(ExampleEntity)装饰器,Nest会基于这个装饰器生成一个专属的注入标识(token),而非直接用Repository<ExampleEntity>类型作为注入标识。Automock必须匹配这个正确的标识才能获取到对应的模拟对象。
修改测试代码,使用getRepositoryToken获取正确的注入标识:
import { TestBed } from "@automock/jest"; import { ExampleService } from "./example.service"; import { ExampleEntity } from "./example.entity"; // 新增导入 import { getRepositoryToken } from "@nestjs/typeorm"; import { Repository } from "typeorm"; describe('ExampleService', () => { let exampleService: ExampleService; let exampleRepository: jest.Mocked<Repository<ExampleEntity>>; beforeAll(() => { const { unit, unitRef } = TestBed.create(ExampleService).compile(); exampleService = unit; // 使用getRepositoryToken获取正确的注入标识 exampleRepository = unitRef.get(getRepositoryToken(ExampleEntity)); console.log(exampleRepository); // 现在能正确获取到模拟对象 }); //... })
本质上,@InjectRepository(ExampleEntity)是告诉Nest注入一个以getRepositoryToken(ExampleEntity)为标识的Repository实例,因此测试中必须用这个标识来定位对应的模拟对象,而非直接使用泛型类型。
内容的提问来源于stack exchange,提问作者Nícolas Amarante
相关产品推荐
相关产品推荐

