【问题标题】:Adding a module mapper to Jest?向 Jest 添加模块映射器?
【发布时间】:2018-11-01 07:02:56
【问题描述】:

tsconfig.jsonpaths 设置如下:

"paths": {
  "@fs/*": ["src/*"], 
  "@test/*": ["test/*"]
  }

所有 @fs/blah/blah 导入在 VSCode 中都可以正常解析。为了让 Jest 使用相同的导入声明,我将 moduleMapper 添加到 jest.config.ts,这是完整的配置:

    module.exports = {
    roots: ["./src"],
    transform: {
        "^.+\\.tsx?$": "ts-jest"
    },
    testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
    moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
    moduleNameMapper: {
        "@fs/*": ["src/*"]
    }
    };

import { isBoolean } from "@fs/is"; 这样的语句无法解析。

当使用相对导入进行更改时,Jest 会解决它 (import { isBoolean } from "./is";)

想法?

【问题讨论】:

    标签: javascript node.js typescript jestjs


    【解决方案1】:

    根据jest documentmoduleNameMapper的键是正则表达式。 (不是全局模式)
    <rootDir> 可以用来引用项目的根目录。 (docs)

    所以,我们可以像下面这样配置:

    moduleNameMapper: {
        "^@fs/(.*)$": "<rootDir>/src/$1"
    }
    

    【讨论】:

    猜你喜欢
    • 2019-09-29
    • 2018-06-14
    • 2018-02-16
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    相关资源
    最近更新 更多