Webpack code splitting breaks jest import with vue

2019-05-02 13:51发布

Jest is throwing an error when trying to load a vueJs component that has dynamic import code.

Component:

<script>
    const Modal = () => import(/* webpackChunkName: "Modal" */ "../pages/common/Modal.vue");

    export default {
        name: "TileEditModal",
        components: {
            Modal
        },
        data() {
            return 
        },
        methods: {
            test() {
                return true;
            }
        }
    }
</script>

Test:

import TileEditModal from "./TileEditModal.vue"

Even with no test running, just importing that component will throw the following error:

  return import( /* webpackChunkName: "Modal" */"../pages/common/Modal.vue");
           ^^^^^^
SyntaxError: Unexpected token import

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
  at Object.<anonymous> (srcVue/pages/landing/TileEditModal.vue.test.js:3:22)

I've tried this solution but it has not worked for me.

I'm using jest-vue-preprocessor with jest:

  "jest": {
    "moduleFileExtensions": [
      "js",
      "vue"
    ],
    "transform": {
      "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
      ".*\\.(vue)$": "<rootDir>/node_modules/jest-vue-preprocessor"
    },
    "clearMocks": true,
    "resetMocks": true,
    "resetModules": true
  },

I have also tried adding env.test preset to babel:

{
    "presets": [
      "es2015",
      "stage-2",
      "stage-0"
    ],
    "env": {
      "test": {
        "presets": [
          "es2015",
          "stage-2",
          "stage-0"
        ]
      }
    } 
  }

So far nothing works, any ideas? I really want to get this code splitting to work on individual components.

1条回答
手持菜刀,她持情操
2楼-- · 2019-05-02 14:32

The solution that worked for me was to use the dynamic import babel plugin but also run jest without cache.

jest --no-cache

Unfortunately running it with cache again after that still fails the test so am not sure what's going on, but it works if I leave --no-cache. Just makes the tests slower.

查看更多
登录 后发表回答