我正在尝试模拟一个TypeORM存储库。我的代码是这样的:
describe('DrawingService', () => {
let service: DrawingService;
let repository: MockType<Repository<Drawing>>;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
DrawingService,
{
provide: getRepositoryToken(Drawing, 'document'),
useFactory: repositoryMockFactory,
},
],
}).compile();
service = module.get<DrawingService>(DrawingService);
repository = module.get(getRepositoryToken(Drawing));
});
it('DrawingService is defined', () => {
expect(service).toBeDefined();
});
}
运行此程序时,Nest返回以下错误,这让我感到困惑:
● DrawingService › DrawingService is defined
Nest could not find DrawingRepository element (this provider does not exist in the current context)
44 |
45 | service = module.get<DrawingService>(DrawingService);
> 46 | repository = module.get(getRepositoryToken(Drawing));
| ^
47 | });
48 |
49 | it('DrawingService is defined', () => {
这不可能是我不恰当地放置提供程序造成的,否则在编译模块时就会出现错误。我也不认为原因是模拟工厂,因为这只是一个简单的玩笑
我能做些什么来解决这个问题?
我真的很傻。事后看来,问题真的很明显。在提供者阵列中,我放置
{
provide: getRepositoryToken(Drawing, 'document'),
useFactory: repositoryMockFactory,
},
但在我分配CCD_ 1以下,什么时候应该是repository = module.get(getRepositoryToken(Drawing, 'document'))