NestJS Global Modules in tests

孤街醉人 提交于 2021-01-27 06:45:48

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/55174802/nestjs-global-modules-in-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!