Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to run tests because Nest can't found a module

Tags:

nestjs

I have followed the unit test example but I am unable to run a test, i don't know why it doesn't work. I have this following error : Cannot find module 'src/Application/Auth/Command/LoginCommandHandler' from 'LoginCommandHandler.spec.ts' but my handler is correctly imported. Thanks for your help.

Here is my unit test:

import { LoginCommandHandler } from 'src/Application/Auth/Command/LoginCommandHandler';
import { UserRepository } from 'src/Infrastructure/User/Repository/UserRepository';
import { EncryptionAdapter } from 'src/Infrastructure/Adapter/EncryptionAdapter';

// ...

const module: TestingModule = await Test.createTestingModule({
      providers: [LoginCommandHandler, UserRepository, EncryptionAdapter],
    }).compile();

    userRepository = module.get(UserRepository);
    encryptionAdapter = module.get(EncryptionAdapter);
    handler = new LoginCommandHandler(userRepository, encryptionAdapter);

Here is my src/Application/Auth/Command/LoginCommandHandler/LoginCommandHandler :

export class LoginCommandHandler {
  constructor(
    @Inject('IUserRepository')
    private readonly userRepository: IUserRepository,
    @Inject('IEncryptionAdapter')
    private readonly encryptionAdapter: IEncryptionAdapter,
  ) {}
// ...

And here is my AuthModule :

@Module({
  imports: [
    // ...
    TypeOrmModule.forFeature([User]),
  ],
  providers: [
    // ...
    { provide: 'IUserRepository', useClass: UserRepository },
    { provide: 'IEncryptionAdapter', useClass: EncryptionAdapter },
    LoginCommandHandler,
  ],
})
export class AuthModule {}

like image 787
Mathieu Marchois Avatar asked Jun 21 '19 12:06

Mathieu Marchois


2 Answers

Add this to your jest config in the package.json file:

"moduleNameMapper": {
  "^src/(.*)$": "<rootDir>/$1"
}
like image 183
Eliezer Steinbock Avatar answered Sep 23 '22 09:09

Eliezer Steinbock


Jest is having trouble finding the module related to the absolute path you are using to import. You can find more information at this stackoverflow question.

In short, you just need to tell Jest about where to look for your modules (either in the moduleDirectories field from the jest.config, or in the moduleNameMapper also in the jest.config)

like image 26
Jay McDoniel Avatar answered Sep 19 '22 09:09

Jay McDoniel