【问题标题】:Jest doesn't achieve to import module who imports modules using _moduleAliasesJest 无法导入使用 _moduleAliases 导入模块的模块
【发布时间】:2021-06-22 12:19:52
【问题描述】:

我的模块以这种方式导入模块:

const { Item, Item1 } = require('@v2/helpers');

这是我的 package.json:

"_moduleAliases": { "@v2/helpers": "src/v2-helpers" }

然后在测试文件中,我尝试导入以上述方式导入的文件,但由于 Jest 无法导入这些模块而失败。

Test suite failed to run

    Cannot find module '@v2/helpers' from 'src/path/to/my-module.js'

怎么办?

【问题讨论】:

    标签: node.js jestjs package.json module-alias


    【解决方案1】:

    尝试使用moduleNameMapper

    • 在 package.json 中
    {
      "": "... rest of the package.json",
    
      "jest": {
        "moduleNameMapper": {
          "@v2/helpers": "src/v2-helpers"
        }
      }
    }
    
    • 或在开玩笑的配置中(jest.config.js)
    const {defaults} = require('jest-config');
    const {_moduleAliases} = require('./package.json');
    
    module.exports = async () => {
      return {
        ...defaults,
        // rest of the configuration
        moduleNameMapper: _moduleAliases
      }
    }
    

    【讨论】:

    • 第一种方法有效,第二种方法没有我得到验证错误:必须指定配置选项rootDir
    • 没测试过,可能要添加默认值as shown here(也更新了答案)
    猜你喜欢
    • 2021-10-25
    • 2017-09-08
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2021-01-21
    相关资源
    最近更新 更多