diff --git a/.babelrc b/.babelrc new file mode 100644 index 00000000..41789cac --- /dev/null +++ b/.babelrc @@ -0,0 +1,5 @@ +{ + "presets": ["es2015", "stage-2"], + "plugins": ["transform-runtime"], + "comments": false +} diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..9d08a1a8 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 2 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 00000000..85a83760 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,16 @@ +module.exports = { + root: true, + // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style + extends: 'standard', + // required to lint *.vue files + plugins: [ + 'html' + ], + // add your custom rules here + 'rules': { + // allow paren-less arrow functions + 'arrow-parens': 0, + // allow debugger during development + 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..be86a2b1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.DS_Store +node_modules/ +dist/ +npm-debug.log +selenium-debug.log +test/unit/coverage +test/e2e/reports diff --git a/README.md b/README.md new file mode 100644 index 00000000..7c286977 --- /dev/null +++ b/README.md @@ -0,0 +1,546 @@ +# (1/2)Vue构建单页应用最佳实战 + +标签(空格分隔): 翻译练习 + +--- + +## 前言 + +我们将会选择使用一些vue周边的库 + +1.使用node.js后台,了解到如何获取数据 +2.实现单页路由 +3.实现HTTP请求我们的node +4.单项数据流 +5.使用.vue文件进行开发 + +最终我们将会构建出一个小demo,不废话,直接上图。 +![](http://7xim8z.com1.z0.glb.clouddn.com/vue-tutorial-4.png) + + +## 安装 + +1.我们将会使用webpack去为我们的模块打包,预处理,热加载。如果你对webpack不熟悉,它就是可以帮助我们把多个js文件打包为1个入口文件,并且可以达到按需加载。这就意味着,我们不用去担心由于太多的组件,导致了过多的HTTP请求,这是非常有益于产品体验的。但,我们并不只是为了这个而使用webpack,我们需要用webpack去编译.vue文件,如果没有使用一个loader去转换我们.vue文件里的style,js,html,那么浏览器就无法识别。 + +2.模块热加载是webpack的一个非常碉堡的特性,将会为我们的单页应用带来极大的便利。 +通常来说,当我们修改了代码刷新页面,那应用里的所有状态就都没有了。这对于开发一个单页应用来说是非常痛苦的,因为需要重新在跑一遍流程。如果有模块热加载,当你修改了代码,你的代码会直接修改,页面并不会刷新,所以状态也会被保留。 + +3.Vue也为我们提供了CSS预处理,所以我们可以选择在.vue文件里写LESS或者SASS去代替原生CSS。 + +4.我们过去通常需要使用npm下载一堆的依赖,但是现在我们可以选择Vue-cli。这是一个vue生态系统中一个伟大创举。这意味着我们不需要手动构建我们的项目,而它就可以很快地为我们生成。 + +首先,安装vue-cli。(确保你有node和npm) + +`npm i -g vue-cli` + +然后创建一个webpack项目并且下载依赖 + +`vue init webpack vue-time-tracker` +`cd vue-time-tracker` +`npm i` + +接着使用 `npm run dev` 在热加载中运行我们的应用 + +这一行命令代表着它会去找到`package.json`的`scripts`对象,执行`node bulid/dev-server.js`。在这文件里,配置了Webpack,会让它去编译项目文件,并且运行服务器,我们在`localhost:8080`即可查看我们的应用。 + +![](https://cdn.scotch.io/9/vFba0QgQRReyNZPgFpKU_vue-time-1.png) + +这些都准备好后,我们需要为我们的路由和XHR请求下载两个库,我们可以从vue的官网中找到他们。 + +`npm i vue-resource vue-router --save` + +### 初始化(main.js) + +查看我们的应用文件,我们可以在src目录下找到`App.vue`和`main.js`。在`main.js`文件中,我们引入`Vue`和`App`,并且创建了一个vue的实例(因为在router这行引入了App组件`router.start(App, '#app')`) + +```javascript +// src/main.js + +import Vue from 'vue' +import App from './App.vue' +import Hello from './components/Hello.vue' + +import VueRouter from 'vue-router' +import VueResource from 'vue-resource' + +//注册两个插件 +Vue.use(VueResource) +Vue.use(VueRouter) + +const router = new VueRouter() + +// 路由map +router.map({ + '/hello': { + component: Hello + } +}) + +router.redirect({ + '*': '/hello' +}) + +router.start(App, '#app') +``` + +我们还需要在`index.html`包裹下我们的`` + +```html +//index.html + +
+ +
+``` + +我们的初始化就到这结束了,接下来让我们开始创建别的组件。 + + +### 创建首页 View + +首先,我们需要为我们的应用增加下bootstrap.css,为了方便,在这就直接在头部引入CDN。 + +```html + + + 计划板 + + +``` + +接着在App.vue里为我们的应用写个顶部导航。 + +```js +// src/App.vue + + +``` + +除了我们的`navbar`以外,我们还需要一个`.container`去放我们其余需要展示的信息。 +并且在这里我们要放一个`router-view`标签,`vue-router`的切换就是通过这个标签开始显现的。 + +接着,我们需要创建一个`Home.vue`作为我们的首页 + +```js +// src/components/Home.vue + + +``` + +既然我们需要显示Home,那就需要开始配置路由,这很简单,只需要在`main.js`里把`Hello.vue`换为`Home.vue`即可 + +```js +//... +router.map({ + '/Home': { + component: Home + } +}) + +router.redirect({ + '*': '/Home' +}) +``` + +![](http://7xim8z.com1.z0.glb.clouddn.com/vue-tutorial-1.png) + + +### 创建 任务列表 View + +在这个页面,我们需要去创建我们的时间跟踪列表。 + +> PS:现在这个页面没有数据,之后我们会在后台配置 + +```js + +// src/components/TimeEntries.vue + + +``` + +关于template的解释,都写在一起了,再看看我们的`script` + +```js +// src/components/TimeEntries.vue + + +``` + +别忘了为我们的组件写上一些需要的样式 +```js +// src/components/TimeEntries.vue + + +``` + +由于新增了页面,所以我们继续配置我们的路由 + +```js +// src/main.js + +import TimeEntries from './components/TimeEntries.vue' + +//... + +router.map({ + '/home': { + component: Home + }, + '/time-entries': { + component: TimeEntries + } +}) + +//... +``` + +![](http://7xim8z.com1.z0.glb.clouddn.com/vue-tutorial-2.png) + + +### 创建任务组件 + +这个比较简单我们直接给出代码 + +```js +// src/components/LogTime.vue + + + + + +``` + +这个组件很简单就3个input输入而已,然后就两个按钮,保存我们就把数据push进我们的列表里,并且初始化我们的timeEntry。取消的话,我们就路由定位到`/time-entries`即可。 + +> ps:按理来说我们应该是要填写6个数据包括名字,邮箱和头像。但这里为了演示就暂时先这样。以后结合后台我们会继续完善这里。 + +`LogTime`属于我们`TimeEntries`组件的一个子路由,所以我们依旧需要配置下我们的`router.map` + +```js +// src/main.js + +import LogTime from './components/LogTime.vue' + +//... + +router.map({ + '/home': { + component: Home + }, + '/time-entries': { + component: TimeEntries, + subRoutes: { + '/log-time': { + component: LogTime + } + } + } +}) + +//... +``` + +![](http://7xim8z.com1.z0.glb.clouddn.com/vue-tutorial-3.png) + +### 创建侧边栏组件 + +目前我们首页左侧还有一块空白,我们需要它放下一个侧边栏去统计所有计划的总时间。 + +```js +// src/App.vue + + //... + +
+
+ +
+
+ +
+
+ + //... +``` + +由于我们把总时间存放在最上级的父组件上,所以我们需要把我们的总时间传入我们的`sidebar`组件。 + +在写下我们的两个时间计算方法 + +```js + +``` + +最后给出我们`Sidebar.vue` +``` + + + +``` + +`props`就是vue中传值的写法,不仅要在我们自定义的标签上传入` `,还需要在组件里js里定义`props: ['time']` + + +### 最后 + +本章,我们可以学习到许多关于vue的特性。 +1.了解了vue-cli脚手架 +2.初步对webpack有了一些了解和认识 +3.如何用.vue愉快的开发 +4.父子组件通信 +5.路由(子路由)的应用 + +> 下一章,我们将会结合node学习vue-resource,更好的完善我们SPA应用 diff --git a/build/build.js b/build/build.js new file mode 100644 index 00000000..37f5a820 --- /dev/null +++ b/build/build.js @@ -0,0 +1,35 @@ +// https://github.com/shelljs/shelljs +require('shelljs/global') +env.NODE_ENV = 'production' + +var path = require('path') +var config = require('../config') +var ora = require('ora') +var webpack = require('webpack') +var webpackConfig = require('./webpack.prod.conf') + +console.log( + ' Tip:\n' + + ' Built files are meant to be served over an HTTP server.\n' + + ' Opening index.html over file:// won\'t work.\n' +) + +var spinner = ora('building for production...') +spinner.start() + +var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory) +rm('-rf', assetsPath) +mkdir('-p', assetsPath) +cp('-R', 'static/', assetsPath) + +webpack(webpackConfig, function (err, stats) { + spinner.stop() + if (err) throw err + process.stdout.write(stats.toString({ + colors: true, + modules: false, + children: false, + chunks: false, + chunkModules: false + }) + '\n') +}) diff --git a/build/css-loaders.js b/build/css-loaders.js new file mode 100644 index 00000000..b16ff9fe --- /dev/null +++ b/build/css-loaders.js @@ -0,0 +1,36 @@ +var ExtractTextPlugin = require('extract-text-webpack-plugin') + +module.exports = function (options) { + options = options || {} + // generate loader string to be used with extract text plugin + function generateLoaders (loaders) { + var sourceLoader = loaders.map(function (loader) { + var extraParamChar + if (/\?/.test(loader)) { + loader = loader.replace(/\?/, '-loader?') + extraParamChar = '&' + } else { + loader = loader + '-loader' + extraParamChar = '?' + } + return loader + (options.sourceMap ? extraParamChar + 'sourceMap' : '') + }).join('!') + + if (options.extract) { + return ExtractTextPlugin.extract('vue-style-loader', sourceLoader) + } else { + return ['vue-style-loader', sourceLoader].join('!') + } + } + + // http://vuejs.github.io/vue-loader/configurations/extract-css.html + return { + css: generateLoaders(['css']), + postcss: generateLoaders(['css']), + less: generateLoaders(['css', 'less']), + sass: generateLoaders(['css', 'sass?indentedSyntax']), + scss: generateLoaders(['css', 'sass']), + stylus: generateLoaders(['css', 'stylus']), + styl: generateLoaders(['css', 'stylus']) + } +} diff --git a/build/dev-client.js b/build/dev-client.js new file mode 100644 index 00000000..89f00795 --- /dev/null +++ b/build/dev-client.js @@ -0,0 +1,8 @@ +require('eventsource-polyfill') +var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true') + +hotClient.subscribe(function (event) { + if (event.action === 'reload') { + window.location.reload() + } +}) diff --git a/build/dev-server.js b/build/dev-server.js new file mode 100644 index 00000000..35fb9424 --- /dev/null +++ b/build/dev-server.js @@ -0,0 +1,65 @@ +var path = require('path') +var express = require('express') +var webpack = require('webpack') +var config = require('../config') +var proxyMiddleware = require('http-proxy-middleware') +var webpackConfig = process.env.NODE_ENV === 'testing' + ? require('./webpack.prod.conf') + : require('./webpack.dev.conf') + +// default port where dev server listens for incoming traffic +var port = process.env.PORT || config.dev.port +// Define HTTP proxies to your custom API backend +// https://github.com/chimurai/http-proxy-middleware +var proxyTable = config.dev.proxyTable + +var app = express() +var compiler = webpack(webpackConfig) + +var devMiddleware = require('webpack-dev-middleware')(compiler, { + publicPath: webpackConfig.output.publicPath, + stats: { + colors: true, + chunks: false + } +}) + +var hotMiddleware = require('webpack-hot-middleware')(compiler) +// force page reload when html-webpack-plugin template changes +compiler.plugin('compilation', function (compilation) { + compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { + hotMiddleware.publish({ action: 'reload' }) + cb() + }) +}) + +// proxy api requests +Object.keys(proxyTable).forEach(function (context) { + var options = proxyTable[context] + if (typeof options === 'string') { + options = { target: options } + } + app.use(proxyMiddleware(context, options)) +}) + +// handle fallback for HTML5 history API +app.use(require('connect-history-api-fallback')()) + +// serve webpack bundle output +app.use(devMiddleware) + +// enable hot-reload and state-preserving +// compilation error display +app.use(hotMiddleware) + +// serve pure static assets +var staticPath = path.join(config.build.assetsPublicPath, config.build.assetsSubDirectory) +app.use(staticPath, express.static('./static')) + +module.exports = app.listen(port, function (err) { + if (err) { + console.log(err) + return + } + console.log('Listening at http://localhost:' + port + '\n') +}) diff --git a/build/webpack.base.conf.js b/build/webpack.base.conf.js new file mode 100644 index 00000000..e451e822 --- /dev/null +++ b/build/webpack.base.conf.js @@ -0,0 +1,63 @@ +var path = require('path') +var config = require('../config') +var cssLoaders = require('./css-loaders') +var projectRoot = path.resolve(__dirname, '../') + +module.exports = { + entry: { + app: './src/main.js' + }, + output: { + path: config.build.assetsRoot, + publicPath: config.build.assetsPublicPath, + filename: '[name].js' + }, + resolve: { + extensions: ['', '.js', '.vue'], + fallback: [path.join(__dirname, '../node_modules')], + alias: { + 'src': path.resolve(__dirname, '../src'), + 'assets': path.resolve(__dirname, '../src/assets'), + 'components': path.resolve(__dirname, '../src/components') + } + }, + resolveLoader: { + fallback: [path.join(__dirname, '../node_modules')] + }, + module: { + loaders: [ + { + test: /\.vue$/, + loader: 'vue' + }, + { + test: /\.js$/, + loader: 'babel', + include: projectRoot, + exclude: /node_modules/ + }, + { + test: /\.json$/, + loader: 'json' + }, + { + test: /\.html$/, + loader: 'vue-html' + }, + { + test: /\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)(\?.*)?$/, + loader: 'url', + query: { + limit: 10000, + name: path.join(config.build.assetsSubDirectory, '[name].[hash:7].[ext]') + } + } + ] + }, + vue: { + loaders: cssLoaders() + }, + eslint: { + formatter: require('eslint-friendly-formatter') + } +} diff --git a/build/webpack.dev.conf.js b/build/webpack.dev.conf.js new file mode 100644 index 00000000..f8819e01 --- /dev/null +++ b/build/webpack.dev.conf.js @@ -0,0 +1,26 @@ +var webpack = require('webpack') +var merge = require('webpack-merge') +var baseWebpackConfig = require('./webpack.base.conf') +var HtmlWebpackPlugin = require('html-webpack-plugin') + +// add hot-reload related code to entry chunks +Object.keys(baseWebpackConfig.entry).forEach(function (name) { + baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) +}) + +module.exports = merge(baseWebpackConfig, { + // eval-source-map is faster for development + devtool: '#eval-source-map', + plugins: [ + // https://github.com/glenjamin/webpack-hot-middleware#installation--usage + new webpack.optimize.OccurenceOrderPlugin(), + new webpack.HotModuleReplacementPlugin(), + new webpack.NoErrorsPlugin(), + // https://github.com/ampedandwired/html-webpack-plugin + new HtmlWebpackPlugin({ + filename: 'index.html', + template: 'index.html', + inject: true + }) + ] +}) diff --git a/build/webpack.prod.conf.js b/build/webpack.prod.conf.js new file mode 100644 index 00000000..5646b19a --- /dev/null +++ b/build/webpack.prod.conf.js @@ -0,0 +1,56 @@ +var path = require('path') +var config = require('../config') +var webpack = require('webpack') +var merge = require('webpack-merge') +var baseWebpackConfig = require('./webpack.base.conf') +var cssLoaders = require('./css-loaders') +var ExtractTextPlugin = require('extract-text-webpack-plugin') +var HtmlWebpackPlugin = require('html-webpack-plugin') + +module.exports = merge(baseWebpackConfig, { + devtool: config.build.productionSourceMap ? '#source-map' : false, + output: { + path: config.build.assetsRoot, + filename: path.join(config.build.assetsSubDirectory, '[name].[chunkhash].js'), + chunkFilename: path.join(config.build.assetsSubDirectory, '[id].[chunkhash].js') + }, + vue: { + loaders: cssLoaders({ + sourceMap: config.build.productionSourceMap, + extract: true + }) + }, + plugins: [ + // http://vuejs.github.io/vue-loader/workflow/production.html + new webpack.DefinePlugin({ + 'process.env': { + NODE_ENV: '"production"' + } + }), + new webpack.optimize.UglifyJsPlugin({ + compress: { + warnings: false + } + }), + new webpack.optimize.OccurenceOrderPlugin(), + // extract css into its own file + new ExtractTextPlugin(path.join(config.build.assetsSubDirectory, '[name].[contenthash].css')), + // generate dist index.html with correct asset hash for caching. + // you can customize output by editing /index.html + // see https://github.com/ampedandwired/html-webpack-plugin + new HtmlWebpackPlugin({ + filename: process.env.NODE_ENV === 'testing' + ? 'index.html' + : config.build.index, + template: 'index.html', + inject: true, + minify: { + removeComments: true, + collapseWhitespace: true, + removeAttributeQuotes: true + // more options: + // https://github.com/kangax/html-minifier#options-quick-reference + } + }) + ] +}) diff --git a/config.js b/config.js new file mode 100644 index 00000000..a83f2152 --- /dev/null +++ b/config.js @@ -0,0 +1,16 @@ +// see http://vuejs-templates.github.io/webpack for documentation. +var path = require('path') + +module.exports = { + build: { + index: path.resolve(__dirname, 'dist/index.html'), + assetsRoot: path.resolve(__dirname, 'dist'), + assetsSubDirectory: 'static', + assetsPublicPath: '/', + productionSourceMap: true + }, + dev: { + port: 8080, + proxyTable: {} + } +} diff --git a/index.html b/index.html new file mode 100644 index 00000000..cbe9dae7 --- /dev/null +++ b/index.html @@ -0,0 +1,15 @@ + + + + + 计划 + + + + +
+ +
+ + + diff --git a/package.json b/package.json new file mode 100644 index 00000000..b27e57ec --- /dev/null +++ b/package.json @@ -0,0 +1,75 @@ +{ + "name": "test", + "version": "0.1.0", + "description": "A Vue.js project", + "author": "kodo <524580860@qq.com>", + "private": true, + "scripts": { + "dev": "node build/dev-server.js", + "build": "node build/build.js", + "unit": "karma start test/unit/karma.conf.js --single-run", + "e2e": "node test/e2e/runner.js", + "test": "npm run unit && npm run e2e" + }, + "dependencies": { + "babel-runtime": "^5.8.0", + "vue": "^1.0.18", + "vue-resource": "^0.7.0", + "vue-router": "^0.7.13" + }, + "devDependencies": { + "babel-core": "^6.0.0", + "babel-loader": "^6.0.0", + "babel-plugin-transform-runtime": "^6.0.0", + "babel-preset-es2015": "^6.0.0", + "babel-preset-stage-2": "^6.0.0", + "chai": "^3.5.0", + "chromedriver": "^2.21.2", + "connect-history-api-fallback": "^1.1.0", + "cross-spawn": "^2.1.5", + "css-loader": "^0.23.0", + "eslint": "^2.0.0", + "eslint-config-standard": "^5.1.0", + "eslint-friendly-formatter": "^1.2.2", + "eslint-loader": "^1.3.0", + "eslint-plugin-html": "^1.3.0", + "eslint-plugin-promise": "^1.0.8", + "eslint-plugin-standard": "^1.3.2", + "eventsource-polyfill": "^0.9.6", + "express": "^4.13.3", + "extract-text-webpack-plugin": "^1.0.1", + "file-loader": "^0.8.4", + "function-bind": "^1.0.2", + "html-webpack-plugin": "^2.8.1", + "http-proxy-middleware": "^0.12.0", + "inject-loader": "^2.0.1", + "isparta-loader": "^2.0.0", + "json-loader": "^0.5.4", + "karma": "^0.13.15", + "karma-coverage": "^0.5.5", + "karma-mocha": "^0.2.2", + "karma-phantomjs-launcher": "^1.0.0", + "karma-sinon-chai": "^1.2.0", + "karma-sourcemap-loader": "^0.3.7", + "karma-spec-reporter": "0.0.24", + "karma-webpack": "^1.7.0", + "lolex": "^1.4.0", + "mocha": "^2.4.5", + "nightwatch": "^0.8.18", + "ora": "^0.2.0", + "phantomjs-prebuilt": "^2.1.3", + "selenium-server": "2.53.0", + "shelljs": "^0.6.0", + "sinon": "^1.17.3", + "sinon-chai": "^2.8.0", + "url-loader": "^0.5.7", + "vue-hot-reload-api": "^1.2.0", + "vue-html-loader": "^1.0.0", + "vue-loader": "^8.2.1", + "vue-style-loader": "^1.0.0", + "webpack": "^1.12.2", + "webpack-dev-middleware": "^1.4.0", + "webpack-hot-middleware": "^2.6.0", + "webpack-merge": "^0.8.3" + } +} diff --git a/src/App.vue b/src/App.vue new file mode 100644 index 00000000..4ecf8ec5 --- /dev/null +++ b/src/App.vue @@ -0,0 +1,48 @@ + + + diff --git a/src/assets/logo.png b/src/assets/logo.png new file mode 100644 index 00000000..f3d2503f Binary files /dev/null and b/src/assets/logo.png differ diff --git a/src/components/Home.vue b/src/components/Home.vue new file mode 100644 index 00000000..d0a1b3e2 --- /dev/null +++ b/src/components/Home.vue @@ -0,0 +1,21 @@ + + + + + diff --git a/src/components/LogTime.vue b/src/components/LogTime.vue new file mode 100644 index 00000000..9a8d997a --- /dev/null +++ b/src/components/LogTime.vue @@ -0,0 +1,64 @@ + + + diff --git a/src/components/Sidebar.vue b/src/components/Sidebar.vue new file mode 100644 index 00000000..8ef36da4 --- /dev/null +++ b/src/components/Sidebar.vue @@ -0,0 +1,18 @@ + + + diff --git a/src/components/TimeEntries.vue b/src/components/TimeEntries.vue new file mode 100644 index 00000000..60394e6e --- /dev/null +++ b/src/components/TimeEntries.vue @@ -0,0 +1,117 @@ + + + diff --git a/src/main.js b/src/main.js new file mode 100644 index 00000000..9cd8f454 --- /dev/null +++ b/src/main.js @@ -0,0 +1,36 @@ +import Vue from 'vue' +import App from './App.vue' +import Home from './components/Home.vue' +import TimeEntries from './components/TimeEntries.vue' +import LogTime from './components/LogTime.vue' +import VueRouter from 'vue-router' +import VueResource from 'vue-resource' + +// We want to apply VueResource and VueRouter +// to our Vue instance +Vue.use(VueResource) +Vue.use(VueRouter) + +const router = new VueRouter() + +// Pointing routes to the components they should use +router.map({ + '/Home': { + component: Home + }, + '/time-entries': { + component: TimeEntries, + subRoutes: { + '/log-time': { + component: LogTime + } + } + } +}) + +// Any invalid route will redirect to home +router.redirect({ + '*': '/Home' +}) + +router.start(App, '#app') diff --git a/static/.gitkeep b/static/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/test/e2e/custom-assertions/elementCount.js b/test/e2e/custom-assertions/elementCount.js new file mode 100644 index 00000000..c0d5fe00 --- /dev/null +++ b/test/e2e/custom-assertions/elementCount.js @@ -0,0 +1,26 @@ +// A custom Nightwatch assertion. +// the name of the method is the filename. +// can be used in tests like this: +// +// browser.assert.elementCount(selector, count) +// +// for how to write custom assertions see +// http://nightwatchjs.org/guide#writing-custom-assertions +exports.assertion = function (selector, count) { + this.message = 'Testing if element <' + selector + '> has count: ' + count + this.expected = count + this.pass = function (val) { + return val === this.expected + } + this.value = function (res) { + return res.value + } + this.command = function (cb) { + var self = this + return this.api.execute(function (selector) { + return document.querySelectorAll(selector).length + }, [selector], function (res) { + cb.call(self, res) + }) + } +} diff --git a/test/e2e/nightwatch.conf.js b/test/e2e/nightwatch.conf.js new file mode 100644 index 00000000..b5d911ce --- /dev/null +++ b/test/e2e/nightwatch.conf.js @@ -0,0 +1,40 @@ +// http://nightwatchjs.org/guide#settings-file +module.exports = { + "src_folders": ["test/e2e/specs"], + "output_folder": "test/e2e/reports", + "custom_assertions_path": ["test/e2e/custom-assertions"], + + "selenium": { + "start_process": true, + "server_path": "node_modules/selenium-server/lib/runner/selenium-server-standalone-2.53.0.jar", + "host": "127.0.0.1", + "port": 4444, + "cli_args": { + "webdriver.chrome.driver": require('chromedriver').path + } + }, + + "test_settings": { + "default": { + "selenium_port": 4444, + "selenium_host": "localhost", + "silent": true + }, + + "chrome": { + "desiredCapabilities": { + "browserName": "chrome", + "javascriptEnabled": true, + "acceptSslCerts": true + } + }, + + "firefox": { + "desiredCapabilities": { + "browserName": "firefox", + "javascriptEnabled": true, + "acceptSslCerts": true + } + } + } +} diff --git a/test/e2e/runner.js b/test/e2e/runner.js new file mode 100644 index 00000000..b9f009c5 --- /dev/null +++ b/test/e2e/runner.js @@ -0,0 +1,31 @@ +// 1. start the dev server using production config +process.env.NODE_ENV = 'testing' +var server = require('../../build/dev-server.js') + +// 2. run the nightwatch test suite against it +// to run in additional browsers: +// 1. add an entry in test/e2e/nightwatch.conf.json under "test_settings" +// 2. add it to the --env flag below +// For more information on Nightwatch's config file, see +// http://nightwatchjs.org/guide#settings-file +var spawn = require('cross-spawn') +var runner = spawn( + './node_modules/.bin/nightwatch', + [ + '--config', 'test/e2e/nightwatch.conf.js', + '--env', 'chrome,firefox' + ], + { + stdio: 'inherit' + } +) + +runner.on('exit', function (code) { + server.close() + process.exit(code) +}) + +runner.on('error', function (err) { + server.close() + throw err +}) diff --git a/test/e2e/specs/test.js b/test/e2e/specs/test.js new file mode 100644 index 00000000..49bc7f70 --- /dev/null +++ b/test/e2e/specs/test.js @@ -0,0 +1,14 @@ +// For authoring Nightwatch tests, see +// http://nightwatchjs.org/guide#usage + +module.exports = { + 'default e2e tests': function (browser) { + browser + .url('http://localhost:8080') + .waitForElementVisible('#app', 5000) + .assert.elementPresent('.logo') + .assert.containsText('h1', 'Hello World!') + .assert.elementCount('p', 3) + .end() + } +} diff --git a/test/unit/.eslintrc b/test/unit/.eslintrc new file mode 100644 index 00000000..959a4f4b --- /dev/null +++ b/test/unit/.eslintrc @@ -0,0 +1,9 @@ +{ + "env": { + "mocha": true + }, + "globals": { + "expect": true, + "sinon": true + } +} diff --git a/test/unit/index.js b/test/unit/index.js new file mode 100644 index 00000000..42202514 --- /dev/null +++ b/test/unit/index.js @@ -0,0 +1,13 @@ +// Polyfill fn.bind() for PhantomJS +/* eslint-disable no-extend-native */ +Function.prototype.bind = require('function-bind') + +// require all test files (files that ends with .spec.js) +var testsContext = require.context('./specs', true, /\.spec$/) +testsContext.keys().forEach(testsContext) + +// require all src files except main.js for coverage. +// you can also change this to match only the subset of files that +// you want coverage for. +var srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/) +srcContext.keys().forEach(srcContext) diff --git a/test/unit/karma.conf.js b/test/unit/karma.conf.js new file mode 100644 index 00000000..b3348719 --- /dev/null +++ b/test/unit/karma.conf.js @@ -0,0 +1,66 @@ +// This is a karma config file. For more details see +// http://karma-runner.github.io/0.13/config/configuration-file.html +// we are also using it with karma-webpack +// https://github.com/webpack/karma-webpack + +var path = require('path') +var merge = require('webpack-merge') +var baseConfig = require('../../build/webpack.base.conf') +var projectRoot = path.resolve(__dirname, '../../') + +var webpackConfig = merge(baseConfig, { + // use inline sourcemap for karma-sourcemap-loader + devtool: '#inline-source-map', + vue: { + loaders: { + js: 'isparta' + } + } +}) + +// no need for app entry during tests +delete webpackConfig.entry + +// make sure isparta loader is applied before eslint +webpackConfig.module.preLoaders = webpackConfig.module.preLoaders || [] +webpackConfig.module.preLoaders.unshift({ + test: /\.js$/, + loader: 'isparta', + include: projectRoot, + exclude: /test\/unit|node_modules/ +}) + +// only apply babel for test files when using isparta +webpackConfig.module.loaders.some(function (loader, i) { + if (loader.loader === 'babel') { + loader.include = /test\/unit/ + return true + } +}) + +module.exports = function (config) { + config.set({ + // to run in additional browsers: + // 1. install corresponding karma launcher + // http://karma-runner.github.io/0.13/config/browsers.html + // 2. add it to the `browsers` array below. + browsers: ['PhantomJS'], + frameworks: ['mocha', 'sinon-chai'], + reporters: ['spec', 'coverage'], + files: ['./index.js'], + preprocessors: { + './index.js': ['webpack', 'sourcemap'] + }, + webpack: webpackConfig, + webpackMiddleware: { + noInfo: true + }, + coverageReporter: { + dir: './coverage', + reporters: [ + { type: 'lcov', subdir: '.' }, + { type: 'text-summary' } + ] + } + }) +} diff --git a/test/unit/specs/Hello.spec.js b/test/unit/specs/Hello.spec.js new file mode 100644 index 00000000..835ad99f --- /dev/null +++ b/test/unit/specs/Hello.spec.js @@ -0,0 +1,12 @@ +import Vue from 'vue' +import Hello from 'src/components/Hello' + +describe('Hello.vue', () => { + it('should render correct contents', () => { + const vm = new Vue({ + template: '
', + components: { Hello } + }).$mount() + expect(vm.$el.querySelector('.hello h1').textContent).to.contain('Hello World!') + }) +})