mardi 31 décembre 2019

Mock multiple TypeORM repositories in NestJS

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.

Thanks in advance!

1 commentaire:

  1. Hi @mardi, have you been able to solve this problem?? I have been stuck here for 48 hours now

    RépondreSupprimer