【问题标题】:babel-plugin-module-resolver doesnt work with jestbabel-plugin-module-resolver 不适用于 jest
【发布时间】:2019-07-18 19:50:52
【问题描述】:

Babel 别名适用于测试文件本身,但不适用于 vue 文件中的导入。

我遇到了error when jest try import file in vue file这样的错误

我将 moduleNameMapper 添加到 jest 配置中,但只有当我删除 babel-plugin-module-resolver 并在 webpack 中添加别名时他才起作用。这个解决方案不适合我,因为我们所有的项目都有相同的别名表示方式

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

recovery.test.js

import { wrap } from '~/utils/test';
import recovery from '~/popup/router/pages/recovery/recovery';
import captcha from '~/components/captcha/captcha';
import ELInput from 'element-ui/lib/input';

recovery.vue

import punycode from 'punycode';
import { mapActions, mapState } from 'vuex';
import captcha from '~/components/captcha/captcha';
import { RECOVERY_PASSWORD, RECOVERY_PASSWORD_SUCCESS, RECOVERY_PASSWORD_FAILURE         
} from '~/store/recovery/events';
import ssid from '~/mixins/ssid';
import { w3cValidateEmail, getConfig } from '~/helpers/index';

.babelrc

{
  "plugins": [
    "@babel/plugin-proposal-optional-chaining",
    ["module-resolver", {
        "alias": {
          "~": "./src"
        }
    }]

  ],
  "presets": [
    ["@babel/preset-env", {
        "useBuiltIns": "usage",
        "targets": {
            "browsers": ["> 0.25%", "not ie 11", "not op_mini all"]
        }
    }]
  ],
  "env": {
    "test": {
      "presets": [
        ["env", { "targets": { "node": "current" }}]
      ]
    }
  }
}

jest.config.js

module.exports = {
setupFiles: [
    "./jest.setup.js"
],
moduleFileExtensions: [
    "js",
    "vue"
],
transform: {
    "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
    ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
},
testPathIgnorePatterns: [
    '<rootDir>/initTest.js', 
    '<rootDir>/utils',
    '<rootDir>/node_modules'
],
testMatch: [
    "**/*.test.js"
],
collectCoverage: true,
collectCoverageFrom: [
    "**/src/components/**/*.vue",
    "**/src/options/**/**/*.vue",
    "**/src/helpers/index.js",
    "**/src/popup/router/pages/**/**.vue",
],
coveragePathIgnorePatterns: [
    "src/popup/router/pages/Index.vue"
],
coverageThreshold: {
    global: {
        statements: 50,
        branches: 20,
        lines: 50,
        functions: 40,
    },
},
};

【问题讨论】:

  • 如果我从 .babelrc 中删除模块解析器并在 jest.config.js 中添加 moduleNameMapper 也可以测试。我不明白为什么别名 jest.config.js 与 babelrc 冲突
  • 你解决了吗?

标签: vue.js jestjs babeljs


【解决方案1】:

我刚刚解决了这个问题,所以如果有人在搜索这个问题时遇到这个问题,这里是问题的原因和我的解决方案。

真正的问题是什么?

.babelrc module-resolver 覆盖 jest moduleNameMapper

工作解决方案:

您可以在除 test 之外的任何 NODE_ENV 中使用 babel 模块解析器,因此我们将在运行 jest 测试时使用 moduleNameMapper

我们可以在 babel 中通过将 .babelrc 转换为 .babelrc.js 并检查 process.env 中的 NODE_ENV 如果它等于测试,则不要将 module-resolver 推送到插件。

【讨论】:

    猜你喜欢
    • 2019-05-19
    • 2019-04-06
    • 2020-07-07
    • 2020-07-29
    • 2019-05-02
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    相关资源
    最近更新 更多