冒烟测试的作用是在版本发布的时候,检测项目是否可用,基本功能是否有问题。
比如构建是否成功,是否有js、css、html文件等。
代码案例中只写了html文件的检测。
使用mocha进行冒烟测试。创建测试文件夹smoke,其下创建index.js,代码:
const rimraf = require("rimraf");const path = require("path");const webpack = require("webpack");const Mocha = require("mocha");
// 创建mocha实例
const mocha = new Mocha();
// 删除dist打包文件
rimraf(path.join(__dirname, "../../dist"), () => {// 加载webpack的配置
const webpackProd = require(path.join(__dirname, "../../webpack.config.js"));
// 使用webpack函数执行webpack配置,如果有错,打印出来,并关闭程序 webpack(webpackProd, (err, stats) => { if (err) { console.error(err); process.exit(2); } console.log( stats.toString({ color: true, modules: false, children: false, }) );
// 没有错,则使用mocha的addFile添加测试任务,最后使用mocha的run方法启动。
mocha.addFile(path.join(__dirname, "html-test.js")); mocha.run(); });});
html-test.js文件:
const glob = require("glob");const path = require("path");describe("Checking generated html file", () => { it("should generate html file", (done) => {
// 使用global加载index.html文件,如果存在,使用done方法通过测试用例,如果没有,则抛出错误。 const files = glob.sync(path.join(__dirname, "../../dist/index.html")); if (files.length > 0) { done(); } else { throw new Error("not found index.html"); } });});
在package.json中增加启动命令:"test": "node ./smoke/index.js",使用yarn start即可启动。