babel-plugin-module-resolver doesnt work with jest

Babel alias work for test files itself, but not working for imports in vue files.

I get fault like error when jest try import file in vue file

i add moduleNameMapper to jest config, but he work only when i remove babel-plugin-module-resolver and add alias in webpack. This solution doesnt suit me, cause all our projects has the same way of indicating aliases

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,
    },
},
};

Upvotes: 2

Views: 1311

Answers (1)

Khalifa Gad
Khalifa Gad

Reputation: 381

I just resolved this issue, so here is the cause of the problem and my solution if anyone came across this question searching.

What is the actual problem?

.babelrc module-resolver overrides jest moduleNameMapper

Working solution:

Use babel module resolvers in any NODE_ENV except test, and moduleNameMapper only for testing env.

We can accomplish this in babel by converting .babelrc to .babelrc.js and checking for the NODE_ENV from process.env if it's equal test, don't push module-resolver to the plugins.

Upvotes: 3

Related Questions