本文介绍了测试中的 NestJS 全局模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

有没有办法自动将所有 @Global 模块提供到 TestModule 中?(即无需导入它们,与主应用程序的工作方式相同)

到目前为止,我必须确保将所有全局模块插入到我调用的 import 列表中:

await Test.createTestingModule({进口:[全局模块1,全局模块2
解决方案

全局模块总是需要导入一次,它们的提供者才能在全球可用.这适用于测试主应用程序,请参阅文档.>

全局模块只能注册一次,最好由根或核心模块.之后,CatsService 提供程序将是无处不在,尽管 CatsModule 不会被导入.

因此无法导入它们.您可以通过创建一个导入所有全局模块的 CommonsModule 来简化它.然后,您可以导入 CommonsModule 而不是 AppModule 和测试中的每个模块.

但是请注意,拥有大量全局依赖项是一种代码异味.此外,在单元测试中,您通常希望将类与任何其他依赖项隔离开来.如果您导入全局模块,您将针对实际提供程序进行测试.

让一切都全球化并不是一个好的决定.全局模块可用于减少所需样板的数量.这导入数组仍然是制作模块 API 的最佳方式透明.

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
解决方案

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.

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.

这篇关于测试中的 NestJS 全局模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 13:31