Jest + vue:“无法找到模块.... vue”

时间:2019-11-27 19:04:22

标签: vue.js jestjs

我真的只是想为我的图书馆准备一个开玩笑的骨架,然后迅速得到这个错误。 我知道该结构不是通常的玩笑结构,我在这里尝试描述一个带有辅助控件的测试。

这是我的test文件夹的内容:arrays.specs.tsarrays.vue

这是配置:

module.exports = {
  moduleFileExtensions: [
    "js",
    "ts",
    "vue"
  ],
  roots: [
    "<rootDir>/test"
  ],
  testEnvironment: "jest-environment-jsdom",
  testMatch: [
    "**/?(*.)+(spec|test).[tj]s?(x)"
  ],
  transform: {
    ".*\\.(vue)$": "vue-jest",
    ".*\\.(ts)$": "ts-jest"
  },
};

我已经安装了以下3个软件包:@vue/test-utilsts-jestvue-jest

现在,有了这个,在开玩笑时我仍然会遇到此错误:

    test/arrays.spec.ts:4:20 - error TS2307: Cannot find module './arrays.vue'.

    import Arrays from './arrays.vue'

我真的看不到我想念的东西。

4 个答案:

答案 0 :(得分:2)

您可能缺少一个“垫片”文件。把它放在你的“src”目录中:

shims-vue.d.ts

declare module '*.vue' {
  import Vue from 'vue';
  export default Vue;
}

答案 1 :(得分:1)

如果在vest jest测试中发生错误找不到模块问题,请如下设置 jest.config.js 文件的 preset 属性

module.exports = {
  preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
  testEnvironment: 'node'
}

答案 2 :(得分:0)

npm软件包vue-jest使用的是'babel-core'。如果您从node_modules -> \node_modules\vue-jest\lib\compilers\babel-compiler.js中打开文件,则会看到下面的代码。

const babel = require('babel-core')
const loadBabelConfig = require('../load-babel-config.js')

module.exports = function compileBabel (scriptContent, inputSourceMap, inlineConfig, vueJestConfig, filePath) {
  ...

第一个常量是导入npm软件包babel-core

如果您使用@babel/core进行了更改,则应解决问题。 更改后,它看起来应该像这样:

const babel = require('@babel/core')
const loadBabelConfig = require('../load-babel-config.js')

    module.exports = function compileBabel (scriptContent, inputSourceMap, inlineConfig, vueJestConfig, filePath) {
      ...`

我在网上看到了一些解决方案,他们建议将babel-core(版本6)替换为babe-core(7.0.0.0-bridge)。就我而言,这破坏了我的解决方案,我无法再发布了,但jest在npm上运行良好。 这是针对已经设置了webpack.config.js的人的解决方案,并且他们出于笑话也拥有.babelrc。

要安装@ babel / core:npm install --save-dev @babel/core babel-core是babel版本6,@babel/core是babel版本7。

答案 3 :(得分:0)

就我而言,问题在于文件 shims-vue.d.ts 位于项目的根目录中。我必须将它移到 ./src 才能加载 .vue 模块。

相关问题