cloudtian / blogs

Summary of knowledge and blogs for every little things
3 stars 0 forks source link

在vue项目中搭建jest测试框架 #21

Open cloudtian opened 5 years ago

cloudtian commented 5 years ago

安装相关包:

npm i jest babel-jest vue-jest -D

在package.json里添加测试脚本:

{
  "scripts": {
     "test": "jest",
      ...
  },
  ...
}

配置jest.config.js文件:

module.exports = {
    moduleFileExtensions: [ // 扫描哪些类型的文件
        "js",
        "vue"
    ],
    moduleNameMapper: { // 配置别名
        "^common/(.*)$": "<rootDir>/src/common/$1"
    },
    transform: { // 不同类型文件对应的预处理工具
        "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
        ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
    }
}

问题来了

$ npm run test
> jest
FAIL test/unit/widget/window.test.js
  ● Test suite failed to run
    Cannot find module 'babel-core'

找不到babel-core,当前项目中已经安装了@babel/core@7.3.4
执行命令npm i babel-core -D安装后再次测试

$ npm run test
> jest
FAIL test/unit/widget/window.test.js
  ● Test suite failed to run
    Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you have a compatible version of @babel/core, it is likely that something in your build process is loading the wrong version. Inspect the stack trace of this error to look for the first entry that doesn't mention "@babel/core" or "babel-core" to see what is calling Babel.

原来babel-jest不支持babel7版本,后找到解决方案,需要安装babel-core@^7.0.0-bridge.0插件 卸载掉babel-core后安装npm i babel-core@^7.0.0-bridge.0 -D后再次测试