有没有办法自动将所有 @Global
模块提供给 TestModule
? (即无需导入它们,与主应用程序的工作方式相同)
到目前为止,我必须确保将任何全局模块插入我调用的 import
列表中:
await Test.createTestingModule({
imports: [
GlobalModule1,
GlobalModule2
最佳答案
全局模块总是必须导入一次,以便它们的提供者在全局范围内可用。这适用于测试 和 主应用程序,请参阅 docs .
Global modules shall be registered only once, in best case by the root or core module. Afterwards, the
CatsService
provider will be ubiquitous, althoughCatsModule
won't be imported.
所以没有办法绕过导入它们。您可以通过创建一个导入所有全局模块的 CommonsModule
来简化它。然后,您可以导入 CommonsModule
而不是 AppModule
和测试中的每个模块。
不过请注意,拥有大量全局依赖项是一种代码味道。此外,在单元测试中,您通常希望在与任何其他依赖项隔离的情况下测试一个类。如果您导入全局模块,您将针对实际提供者进行测试。
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.
关于javascript - 测试中的 NestJS 全局模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55174802/