使用vue-cli3 搭建mocha+karma+chai+ci测试环境时候遇到的坑

360 阅读2分钟

踩的坑不是一般的多,想到一个更新一个。

安装以下依赖

"devDependencies": {
        "@vue/cli-plugin-babel": "^4.1.0",
        "@vue/cli-plugin-eslint": "^4.1.0",
        "@vue/cli-service": "^4.1.0",
        "babel-core": "^6.26.3",
        "babel-eslint": "^10.0.3",
        "babel-loader": "^8.0.6",
        "chai": "^4.2.0",
        "eslint": "^5.16.0",
        "eslint-plugin-vue": "^5.0.0",
        "karma": "^4.4.1",
        "karma-chai": "^0.1.0",
        "karma-chrome-launcher": "^3.1.0",
        "karma-mocha": "^1.3.0",
        "karma-webpack": "^4.0.2",
        "karma-sourcemap-loader": "^0.3.7",
        "karma-spec-reporter": "^0.0.32",
        "mocha": "^6.2.2",
        "vue-template-compiler": "^2.6.10",
        "webpack": "^4.41.3"
    }

karma配置中找不到webConfig?

vue-cli3.x创建的项目根目录不再有webpack.config.js,所以在karma.conf.js中加上下行代码

let webpackConfig = require('@vue/cli-service/webpack.config.js')

let webpackConfig = require('@vue/cli-service/webpack.config.js')
module.exports = function(config) {
    config.set({
        frameworks: [
            'mocha',
            'chai'
        ],
        files: [
            'src/test/**/*.spec.js'   //tests目录下,所有.spce.js结尾的测试文件
        ],
        preprocessors: {
            '**/*.spec.js': [
                'webpack',
                'sourcemap'
            ]
        },
        webpack: webpackConfig,
        reporters: ['spec'],
        browsers: ['Chrome']
    })
};

IDE提示'describe'以及'it' is not defined?

.eslintrc.js里面加上mocha:true

module.exports = {
    root: true,
    env: {
        node: true,
        mocha: true
    },
    'extends': [
        'plugin:vue/essential',
        'eslint:recommended'
    ],
    rules: {
        'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
        'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
    },
    parserOptions: {
        parser: 'babel-eslint'
    }
}

ci虚拟环境运行时出错

原因是package.json和package-lock.json里没同步,然后我去package-lock里面寻找我安装的mocha依赖没有看见,所以问题就在这里

解决:删除node_modules和package-lock.json,重新安装依赖

成功收到passed邮件

如何获取测试覆盖率数据,同时每次 Push 或者 Pull Request 时能够将数据上传到 Codecov?在Github中看到当次提交的覆盖率。

安装依赖karma-coverage babel-plugin-istanbul

为啥没有report,因为ci里面配置环境变量的时候设置的是all master,去ci里把token的branch改为coverage

测试单文件

karma运行环境使用无头浏览器的时候报错

解决方案:装依赖phantomjs-polyfill-object-assign,但还是报错,结果是最新的phantomJS浏览器不支持ES2015了,PhantomJS也已经停止维护了,只有改成chrome了
qiaoanran.com/article/0f1…

最新解决方案: stackoverflow.com/questions/4…

引入element插件后报错

但是我在main.js里面已经引用了啊,原因还带探索,查看element-ui/utils后,看到测试js里面引入了element,然后我也给加上,就没有报错啦