简体   繁体   English

测试中的 NestJS 全局模块

[英]NestJS Global Modules in tests

Is there a way to automatically provide all @Global modules into a TestModule ?有没有办法自动将所有@Global模块提供到TestModule中? (ie 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:到目前为止,我必须确保将任何全局模块插入到调用的import列表中:

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

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.之后, CatsService提供程序将无处不在,尽管不会导入CatsModule

So there's no way around importing them.所以没有办法导入它们。 You can make it easier by creating a CommonsModule that imports all your global modules.您可以通过创建一个导入所有全局模块的CommonsModuleCommonsModule它。 You can then import the CommonsModule instead of each module in your AppModule and your tests.然后,您可以导入CommonsModule而不是AppModule和测试中的每个模块。

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.导入数组仍然是使模块 API 透明的最佳方式。

I was having a similar issue with the unit tests for global ConfigModule<\/code> .我在全局ConfigModule<\/code>的单元测试中遇到了类似的问题。 Someone might find it useful so I'm gonna explain it below.有人可能会觉得它很有用,所以我将在下面解释它。

As a minimal configuration, my root module had these values作为最小配置,我的根模块具有这些值

// app.module.ts
@Module({
  imports: [
    RedisModule,
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
      validationSchema: Joi.object({
        REDIS_HOST: Joi.string().required(),
        REDIS_PORT: Joi.number().required(),
        REDIS_USER: Joi.string().optional(),
        REDIS_PASS: Joi.string().optional(),
      }),
      validationOptions: {
        abortEarly: false,
        allowUnknown: true,
      },
    }),
  ],
})
export class AppModule {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM