javascript - 测试中的 NestJS 全局模块

标签 javascript node.js typescript nestjs

有没有办法自动将所有 @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, although CatsModule 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/

相关文章:

angular - 从 json 响应创建动态嵌套组件

angular - 在内容滚动到顶部然后再滚动到底部之前,ionic 3 无限滚动不起作用

javascript - Knex 迁移失败并显示 - SAVEPOINT can only be used in transaction blocks

javascript - 每次在div上滚动时执行jQuery函数

node.js - 如何在 d.ts 文件中声明的接口(interface)中使用 TypeScript 环境声明接口(interface)

javascript - NodeJs错误v-host中间件

javascript - 插入字符串而不是函数

javascript - Ajax 不与 owl-carousel 一起使用

javascript - 如何在同一域中运行两个 React JS 应用程序

node.js - 与 AWS XRAY 一起扬 sails 起航