Skip to content
Advertisement

NestJS Global Modules in tests

Is there a way to automatically provide all @Globalmodules into a TestModule ? (i.e without having to import them, the same way the main application works)

So far, I had to make sure to insert any global modules into the import list of my call:

await Test.createTestingModule({
      imports: [
        GlobalModule1,
        GlobalModule2

Advertisement

Answer

Global modules always have to be imported once for their providers to be available globally. This holds true for tests and the main application, see the docs.

Global modules shall be registered only once, in best case by the root or core module. Afterwards, the CatsService provider will be ubiquitous, although CatsModule won’t be imported.

So there’s no way around importing them. You can make it easier by creating a CommonsModule that imports all your global modules. You can then import the CommonsModule instead of each module in your AppModule and your tests.

Note though, that having lots of global dependencies is a code smell. Also, in unit tests you typically want to test a class in isolation from any other dependencies. If you import the global modules, you will test against the actual providers.

Making everything global is not a good decision. The global modules are available to reduce the amount of necessary boilerplate. The imports array is still the best way to make the module API transparent.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement