2
votes

I'm having trouble to mock multiple repositories from different modules in NestJS.

I'm using a UsersRepository from a UsersModule inside another module service (NotesService). The code is working fine, but I can't make the unit tests work.

I have the following error: Error: Nest can't resolve dependencies of the UserRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.

Minimal reproduction

// [users.module.ts]

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}


// [users.service.ts]

@Injectable()
export class UsersService {
  constructor(@InjectRepository(User) private usersRepository: UsersRepository) {}
  ...
}


// [notes.module.ts]

@Module({
  imports: [
    TypeOrmModule.forFeature([Note, User]),
    UsersModule,
  ],
  controllers: [NotesController],
  providers: [NotesService],
})
export class NotesModule {
}

// [notes.service.ts]

@Injectable()
export class NotesService {
  constructor(
    @InjectRepository(Note) private notesRepository: NotesRepository,
    @InjectRepository(User) private usersRepository: UsersRepository,
  ) {}
  ...
}

Here is my unit test configuration:

// [notes.service.spec.ts]

beforeEach(async () => {
    const module = await Test.createTestingModule({
      imports: [UsersModule],
      providers: [
        NotesService,
        { provide: getRepositoryToken(Note), useFactory: repositoryMockFactory },
        { provide: getRepositoryToken(User), useFactory: repositoryMockFactory },
      ],
    }).compile();

    notesService = module.get<NotesService>(NotesService);
    notesRepositoryMock = module.get(getRepositoryToken(Note));
  });

The problem is I can't make a proper mock of the UsersRepository that comes from another module.

I tried importing TypeOrmModule directly inside the test, and everything I could but I can't make it work.

1

1 Answers

1
votes

You don't need to import the UsersModule if you are directly providing the NotesService and the mocks that it will depend on. The reason for the error is that Nest is trying to resolve TypeormModule.forFeature([User]) from the UsersModule. Simply remove the import in the test and you should be golden.