diff --git a/README.md b/README.md index 832cf32..b3110f5 100644 --- a/README.md +++ b/README.md @@ -1 +1,30 @@ -# blog-components-layout \ No newline at end of file +# blog-tdd-layout + +> A Vue.js project + +## Build Setup + +``` bash +# install dependencies +npm install + +# serve with hot reload at localhost:8080 +npm run dev + +# build for production with minification +npm run build + +# build for production and view the bundle analyzer report +npm run build --report + +# run unit tests +npm run unit + +# run e2e tests +npm run e2e + +# run all tests +npm test +``` + +For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader). diff --git a/back-end-tdd/.gitignore b/back-end-tdd/.gitignore new file mode 100644 index 0000000..b512c09 --- /dev/null +++ b/back-end-tdd/.gitignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/back-end-tdd/README.md b/back-end-tdd/README.md new file mode 100644 index 0000000..4ac03ba --- /dev/null +++ b/back-end-tdd/README.md @@ -0,0 +1 @@ +# blog-tdd \ No newline at end of file diff --git a/back-end-tdd/app.js b/back-end-tdd/app.js new file mode 100644 index 0000000..737854a --- /dev/null +++ b/back-end-tdd/app.js @@ -0,0 +1,59 @@ +var express = require('express'); +var path = require('path'); +var favicon = require('serve-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var cors = require('cors') +var bodyParser = require('body-parser'); +var mongoose = require('mongoose'); +mongoose.connect('mongodb://localhost/blog-tdd'); + +var index = require('./routes/index'); +var artikel = require('./routes/artikel'); +var user = require('./routes/user'); +var login = require('./routes/login'); + +var app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs'); + +// uncomment after placing your favicon in /public +//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(cors()) +app.use(bodyParser.urlencoded({ extended: false })); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); +var db = mongoose.connection; +db.on('error', console.error.bind(console, 'connection error :')) +db.once('open', function(){ + console.log(`Connected`) +}) + +app.use('/', index); +app.use('/api/artikel', artikel); +app.use('/api/user', user); +app.use('/api/login', login); + +// catch 404 and forward to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// error handler +app.use(function(err, req, res, next) { + // set locals, only providing error in development + res.locals.message = err.message; + res.locals.error = req.app.get('env') === 'development' ? err : {}; + + // render the error page + res.status(err.status || 500); + res.render('error'); +}); + +module.exports = app; diff --git a/back-end-tdd/bin/www b/back-end-tdd/bin/www new file mode 100755 index 0000000..aa1db4f --- /dev/null +++ b/back-end-tdd/bin/www @@ -0,0 +1,90 @@ +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var app = require('../app'); +var debug = require('debug')('blog-tdd:server'); +var http = require('http'); + +/** + * Get port from environment and store in Express. + */ + +var port = normalizePort(process.env.PORT || '3000'); +app.set('port', port); + +/** + * Create HTTP server. + */ + +var server = http.createServer(app); + +/** + * Listen on provided port, on all network interfaces. + */ + +server.listen(port); +server.on('error', onError); +server.on('listening', onListening); + +/** + * Normalize a port into a number, string, or false. + */ + +function normalizePort(val) { + var port = parseInt(val, 10); + + if (isNaN(port)) { + // named pipe + return val; + } + + if (port >= 0) { + // port number + return port; + } + + return false; +} + +/** + * Event listener for HTTP server "error" event. + */ + +function onError(error) { + if (error.syscall !== 'listen') { + throw error; + } + + var bind = typeof port === 'string' + ? 'Pipe ' + port + : 'Port ' + port; + + // handle specific listen errors with friendly messages + switch (error.code) { + case 'EACCES': + console.error(bind + ' requires elevated privileges'); + process.exit(1); + break; + case 'EADDRINUSE': + console.error(bind + ' is already in use'); + process.exit(1); + break; + default: + throw error; + } +} + +/** + * Event listener for HTTP server "listening" event. + */ + +function onListening() { + var addr = server.address(); + var bind = typeof addr === 'string' + ? 'pipe ' + addr + : 'port ' + addr.port; + debug('Listening on ' + bind); +} diff --git a/back-end-tdd/controller/cArtikel.js b/back-end-tdd/controller/cArtikel.js new file mode 100644 index 0000000..929bf44 --- /dev/null +++ b/back-end-tdd/controller/cArtikel.js @@ -0,0 +1,87 @@ +const Artikel = require("../model/Artikel"); + +let artikelPost = function(req,res){ + let data = req.body; + + let newArtikel = new Artikel({ + judul : data.judul, + pesan_singkat : data.pesan_singkat, + pesan : data.pesan, + autor : data.autor + }); + + newArtikel.save(function(err,artikel){ + if (err) { + console.log(err) + } else { + res.status(200).send(artikel) + } + }) +} + +let artikelDelete = function(req,res) { + let id = req.params.id; + Artikel.findById(id, function(err, artikel){ + if(err){ + res.status(502).send(`Something Wrong with your Mongodb : ${err}`); + } else { + artikel.remove(function(err) { + if(err){ + res.status(501).send(`Something Wrong with your Mongodb : ${err}`); + } else{ + res.status(200).send(`1 Document Artikel Deleted`) + } + }) + } + }) +} + +let artikelFindById = function(req,res) { + let id = req.params.id; + Artikel.findById(id, function(err, artikel){ + if(err){ + res.status(502).send(`Something Wrong with your Mongodb : ${err}`); + } else { + res.status(200).send(artikel); + } + }) +} + +let artikelGet = function(req,res){ + Artikel.find({}, function(err, artikel){ + if(err){ + res.status(502).send(`Something Wrong with your Mongodb : ${err}`); + } else { + res.status(200).send(artikel); + } + }) +} + +let artikelPut = function(req,res){ + Artikel.findById(req.params.id, (err,artikel) =>{ + if(err){ + res.status(504).send(`Something Wrong with your Mongodb : ${err}`); + } else { + let data = req.body; + artikel.judul = data.judul; + artikel.pesan = data.pesan; + artikel.autor = data.autor; + + artikel.save(function(err,newartikel){ + if (err) { + res.status(506).send(`Something Wrong with your Mongodb : ${err}`); + } else { + res.status(200).send(newartikel); + } + }) + } + }) +} + +module.exports = { +artikelPost, +artikelDelete, +artikelGet, +artikelPut, +artikelFindById +}; \ No newline at end of file diff --git a/back-end-tdd/controller/cLogin.js b/back-end-tdd/controller/cLogin.js new file mode 100644 index 0000000..8a3d2ca --- /dev/null +++ b/back-end-tdd/controller/cLogin.js @@ -0,0 +1,39 @@ +const User = require('../model/User'); +const bcrypt = require('bcrypt'); +const saltRounds = 10; +const jwt = require('jsonwebtoken'); + +let login_post = function (req,res){ + let input = req.body; + User.find({}) + .where('username').equals(input.username) + .exec(function(err,user){ + if (err) { + res.status(501).send(`Something Wrong with your login Error : ${err}`) + } else { + if (user.length <= 0) { + res.status(401).send('Username Wrong, check your username again'); + } else { + bcrypt.compare(input.password, user[0].password, function(err,respone){ + if(err){ + res.status(501).send(`Something Wrong with your login Error : ${err}`); + } else { + if(respone){ + jwt.sign({ + username : user.username, + name : user.name, + email : user.email + },"scret", function(err,token){ + res.status(200).send(token); + }) + } else { + res.status(401).send(`Password Wrong, check your username again ${err}`); + } + } + }) + } + } + }) +} + +module.exports = login_post \ No newline at end of file diff --git a/back-end-tdd/controller/cUser.js b/back-end-tdd/controller/cUser.js new file mode 100644 index 0000000..fc556d2 --- /dev/null +++ b/back-end-tdd/controller/cUser.js @@ -0,0 +1,81 @@ +const User = require("../model/User"); +const bcrypt = require('bcrypt'); +const saltRounds = 10; + +let user_post = (req,res) => { + bcrypt.genSalt(saltRounds, (err,salt)=>{ + var data = req.body; + bcrypt.hash(data.password,salt, (err,hash) =>{ + let newUser = ""; + newUser = User({ + username : data.username, + password : hash, + name : data.name, + email : data.email + }) + + newUser.save(function(err,user){ + if (err) { + res.status(501).send(`Something Wrong with your Add User, Error : ${err}`) + } else { + res.status(200).send(user); + } + }) + }) + }) +} + +let user_get = (req,res) =>{ + User.find({},(err,user) =>{ + if (err) { + res.status(503).send(`Something Wrong with your Find User, Error : ${err}`); + } else { + res.status(200).send(user); + } + }) +} + +let user_put = (req,res) =>{ + bcrypt.genSalt(saltRounds, (err,salt)=>{ + var data = req.body; + bcrypt.hash(data.password,salt, (err,hash) =>{ + User.findById(req.params.id, (err,user)=> { + user.username = data.username; + user.password = hash + user.name = data.name; + user.email = data.email; + + user.save((err,new_user) =>{ + if (err) { + res.status(502).send(`Something Wrong with your Update User, Error : ${err}`); + } else { + res.status(200).send(new_user); + } + }) + }) + }) + }) +} + +let user_delete = (req,res) =>{ + User.findById(req.params.id, (err,user) =>{ + if (err) { + res.status(503).send(`Something Wrong with your Delete User, Error : ${err}`); + } else { + user.remove((err) => { + if (err) { + res.status(504).send(`Something Wrong with your Delete User, Error : ${err}`); + } else { + res.status(200).send("1 Document User Delete") + } + }) + } + }) +} + +module.exports = { + user_post, + user_get, + user_put, + user_delete +}; \ No newline at end of file diff --git a/back-end-tdd/model/Artikel.js b/back-end-tdd/model/Artikel.js new file mode 100644 index 0000000..e0ed18c --- /dev/null +++ b/back-end-tdd/model/Artikel.js @@ -0,0 +1,12 @@ +var mongoose = require('mongoose'); +var Schema = mongoose.Schema; + +var artikelSchema = new Schema({ + judul : String, + pesan : String, + autor : String +}) + +var Artikel = mongoose.model('Artikel', artikelSchema); + +module.exports = Artikel; \ No newline at end of file diff --git a/back-end-tdd/model/User.js b/back-end-tdd/model/User.js new file mode 100644 index 0000000..dab8d62 --- /dev/null +++ b/back-end-tdd/model/User.js @@ -0,0 +1,14 @@ +var mongoose = require('mongoose'); +var Schema = mongoose.Schema; + + +var userSchema = new Schema({ + username : {type: String, require: true}, + password : {type:String, require:true}, + name : {type: String, require:true}, + email : {type: String, require : true} +}) + +var User = mongoose.model('User', userSchema); + +module.exports = User; \ No newline at end of file diff --git a/back-end-tdd/package.json b/back-end-tdd/package.json new file mode 100644 index 0000000..029e007 --- /dev/null +++ b/back-end-tdd/package.json @@ -0,0 +1,23 @@ +{ + "name": "blog-tdd", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www" + }, + "dependencies": { + "bcrypt": "^1.0.2", + "body-parser": "~1.17.1", + "chai": "^4.0.2", + "cookie-parser": "~1.4.3", + "cors": "^2.8.3", + "debug": "~2.6.3", + "ejs": "~2.5.6", + "express": "~4.15.2", + "jsonwebtoken": "^7.4.1", + "mongodb": "^2.2.30", + "mongoose": "^4.11.1", + "morgan": "~1.8.1", + "serve-favicon": "~2.4.2" + } +} diff --git a/back-end-tdd/public/stylesheets/style.css b/back-end-tdd/public/stylesheets/style.css new file mode 100644 index 0000000..9453385 --- /dev/null +++ b/back-end-tdd/public/stylesheets/style.css @@ -0,0 +1,8 @@ +body { + padding: 50px; + font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; +} + +a { + color: #00B7FF; +} diff --git a/back-end-tdd/routes/artikel.js b/back-end-tdd/routes/artikel.js new file mode 100644 index 0000000..e700e61 --- /dev/null +++ b/back-end-tdd/routes/artikel.js @@ -0,0 +1,12 @@ +var express = require('express'); +var router = express.Router(); +var cArtikel = require('../controller/cArtikel'); + +/* GET home page. */ +router.get('/', cArtikel.artikelGet); +router.post('/', cArtikel.artikelPost); +router.put('/:id',cArtikel.artikelPut); +router.get('/:id',cArtikel.artikelFindById); +router.delete('/:id', cArtikel.artikelDelete); + +module.exports = router; \ No newline at end of file diff --git a/back-end-tdd/routes/index.js b/back-end-tdd/routes/index.js new file mode 100644 index 0000000..ecca96a --- /dev/null +++ b/back-end-tdd/routes/index.js @@ -0,0 +1,9 @@ +var express = require('express'); +var router = express.Router(); + +/* GET home page. */ +router.get('/', function(req, res, next) { + res.render('index', { title: 'Express' }); +}); + +module.exports = router; diff --git a/back-end-tdd/routes/login.js b/back-end-tdd/routes/login.js new file mode 100644 index 0000000..502dfb6 --- /dev/null +++ b/back-end-tdd/routes/login.js @@ -0,0 +1,8 @@ +const express = require('express'); +const router = express.Router(); +const cLogin = require('../controller/cLogin'); + +/* GET home page. */ +router.post('/', cLogin); + +module.exports = router; \ No newline at end of file diff --git a/back-end-tdd/routes/user.js b/back-end-tdd/routes/user.js new file mode 100644 index 0000000..d1ad2fb --- /dev/null +++ b/back-end-tdd/routes/user.js @@ -0,0 +1,11 @@ +const express = require('express'); +const router = express.Router(); +const cUser = require('../controller/cUser'); + +/* GET home page. */ +router.post('/', cUser.user_post); +router.get('/', cUser.user_get); +router.put('/:id', cUser.user_put); +router.delete('/:id', cUser.user_delete); + +module.exports = router; \ No newline at end of file diff --git a/back-end-tdd/test/artikel_test.js b/back-end-tdd/test/artikel_test.js new file mode 100644 index 0000000..7507a38 --- /dev/null +++ b/back-end-tdd/test/artikel_test.js @@ -0,0 +1,68 @@ +const chai = require('chai'); +const should = chai.should(); +const chaiHttp = require('chai-http'); +const app = require('../app'); + +chai.use(chaiHttp); + +describe('Test Untuk Memastikan artikel yang di simpan berhasil', function () { + let id = "" + it('Penambahan dengan data Artikel yang sama', function (done) { + chai.request(app) + .post('/api/artikel') + .send({ + judul : "5 Makanan di Hacktiv8", + pesan : "1. Sate, 2. Soto, 3. Gudek, 4. Kol goreng, 5. Tempe Goreng", + autor : "Antoni Angga" + }) + .end(function(err,res){ + res.should.have.status(200); + //ini ngecheck data nya mirip gak + id = res.body._id; + res.should.have.be.a("Object"); + res.body.judul.should.equal("5 Makanan di Hacktiv8"); + res.body.pesan.should.equal("1. Sate, 2. Soto, 3. Gudek, 4. Kol goreng, 5. Tempe Goreng"); + res.body.autor.should.equal("Antoni Angga"); + done(); + }) + }); + it('Menampilkan Data', function(done){ + chai.request(app) + .get('/api/artikel') + .end(function(err,res){ + res.should.have.status(200); + res.should.have.be.a("Object"); + res.body[0].judul.should.equal("5 Makanan di Hacktiv8"); + res.body[0].pesan.should.equal("1. Sate, 2. Soto, 3. Gudek, 4. Kol goreng, 5. Tempe Goreng"); + res.body[0].autor.should.equal("Antoni Angga"); + done(); + }) + }) + + it('Update Data', (done)=>{ + chai.request(app) + .put(`/api/artikel/${id}`) + .send({"judul":"5 Makanan di Hacktiv8", "pesan" : "1. ayam goreng, 2. Soto, 3. Gudek, 4. Kol goreng, 5. Tempe Goreng", "autor" : "Antoni Angga"}) + .end(function(err,res) { + res.should.have.status(200); + res.should.have.be.a("Object") + res.body.judul.should.equal("5 Makanan di Hacktiv8"); + res.body.pesan.should.equal("1. ayam goreng, 2. Soto, 3. Gudek, 4. Kol goreng, 5. Tempe Goreng"); + res.body.autor.should.equal("Antoni Angga"); + done(); + }) + }) + + it('Hapus Data', function(done) { + chai.request(app) + .delete(`/api/artikel/${id}`) + .end(function(err,res) { + res.should.have.status(200); + res.text.should.equal("1 Document Artikel Deleted"); + done(); + }) + }) +}) + + + \ No newline at end of file diff --git a/back-end-tdd/test/login_test.js b/back-end-tdd/test/login_test.js new file mode 100644 index 0000000..029c01a --- /dev/null +++ b/back-end-tdd/test/login_test.js @@ -0,0 +1,22 @@ +const chai = require('chai'); +const should = chai.should(); +const chaiHttp = require('chai-http'); +const app = require('../app'); + +chai.use(chaiHttp); + +describe('Login kembalikan Token', function () { + it('login benar dan kembalikan token', function () { + chai.request(app) + .post('/api/login') + .send({ + username : "Admin", + password : "admin112" + }) + .end(function(err,res){ + res.should.have.status(200); + res.text.should.be.a('string'); + should.exist(res.text); + }) + }); +}); \ No newline at end of file diff --git a/back-end-tdd/test/user_test.js b/back-end-tdd/test/user_test.js new file mode 100644 index 0000000..1f08d78 --- /dev/null +++ b/back-end-tdd/test/user_test.js @@ -0,0 +1,67 @@ +const chai = require('chai'); +const should = chai.should(); +const chaiHttp = require('chai-http'); +const app = require('../app'); + +chai.use(chaiHttp); + +describe('Create new Account', function () { + let id = ""; + it('Penambahan dengan data User yang sama', function (done) { + chai.request(app) + .post('/api/user') + .send({ + username : "Admin", + password : "admin123", + name : "Antoni Angga", + email : "antoniangga14@gmail.com" + }) + .end(function(err,res){ + res.should.have.status(200); + res.should.have.be.a("Object"); + id = res.body._id; + res.body.username.should.equal("Admin"); + res.body.name.should.equal("Antoni Angga"); + res.body.email.should.equal("antoniangga14@gmail.com"); + done(); + }) + }); + + it("Menampikan Data User", function(done) { + chai.request(app) + .get('/api/user') + .end(function(err,res) { + res.should.have.status(200); + res.should.have.be.a("Object"); + res.body[0].username.should.equal("Admin"); + res.body[0].name.should.equal("Antoni Angga"); + res.body[0].email.should.equal("antoniangga14@gmail.com"); + done(); + }) + }); + + it("Update Data User", function(done){ + chai.request(app) + .put(`/api/user/${id}`) + .send({username : "Admin", name : "Antoni", email : "antoniangga14@gmail.com"}) + .end((err,res)=>{ + res.should.have.status(200); + res.should.have.be.a("Object"); + res.body.username.should.equal("Admin"); + res.body.name.should.equal("Antoni"); + res.body.email.should.equal("antoniangga14@gmail.com"); + done(); + }) + }); + + it("Delete Data User", function(done) { + chai.request(app) + .delete(`/api/user/${id}`) + .end((err,res)=>{ + res.should.have.status(200); + res.text.should.equal("1 Document User Delete"); + done(); + }) + }); + +}); \ No newline at end of file diff --git a/back-end-tdd/views/error.ejs b/back-end-tdd/views/error.ejs new file mode 100644 index 0000000..7cf94ed --- /dev/null +++ b/back-end-tdd/views/error.ejs @@ -0,0 +1,3 @@ +

<%= message %>

+

<%= error.status %>

+
<%= error.stack %>
diff --git a/back-end-tdd/views/index.ejs b/back-end-tdd/views/index.ejs new file mode 100644 index 0000000..7b7a1d6 --- /dev/null +++ b/back-end-tdd/views/index.ejs @@ -0,0 +1,11 @@ + + + + <%= title %> + + + +

<%= title %>

+

Welcome to <%= title %>

+ + diff --git a/front-end-tdd/.babelrc b/front-end-tdd/.babelrc new file mode 100644 index 0000000..c06df4d --- /dev/null +++ b/front-end-tdd/.babelrc @@ -0,0 +1,18 @@ +{ + "presets": [ + ["env", { + "modules": false, + "targets": { + "browsers": ["> 1%", "last 2 versions", "not ie <= 8"] + } + }], + "stage-2" + ], + "plugins": ["transform-runtime"], + "env": { + "test": { + "presets": ["env", "stage-2"], + "plugins": ["istanbul"] + } + } +} diff --git a/front-end-tdd/.editorconfig b/front-end-tdd/.editorconfig new file mode 100644 index 0000000..9d08a1a --- /dev/null +++ b/front-end-tdd/.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/front-end-tdd/.eslintignore b/front-end-tdd/.eslintignore new file mode 100644 index 0000000..34af377 --- /dev/null +++ b/front-end-tdd/.eslintignore @@ -0,0 +1,2 @@ +build/*.js +config/*.js diff --git a/front-end-tdd/.eslintrc.js b/front-end-tdd/.eslintrc.js new file mode 100644 index 0000000..67c085d --- /dev/null +++ b/front-end-tdd/.eslintrc.js @@ -0,0 +1,27 @@ +// http://eslint.org/docs/user-guide/configuring + +module.exports = { + root: true, + parser: 'babel-eslint', + parserOptions: { + sourceType: 'module' + }, + env: { + browser: 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 async-await + 'generator-star-spacing': 0, + // allow debugger during development + 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 + } +} diff --git a/front-end-tdd/.gitignore b/front-end-tdd/.gitignore new file mode 100644 index 0000000..4105b14 --- /dev/null +++ b/front-end-tdd/.gitignore @@ -0,0 +1,16 @@ +.DS_Store +node_modules/ +dist/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +test/unit/coverage +test/e2e/reports +selenium-debug.log + +# Editor directories and files +.idea +*.suo +*.ntvs* +*.njsproj +*.sln diff --git a/front-end-tdd/.postcssrc.js b/front-end-tdd/.postcssrc.js new file mode 100644 index 0000000..ea9a5ab --- /dev/null +++ b/front-end-tdd/.postcssrc.js @@ -0,0 +1,8 @@ +// https://github.com/michael-ciniawsky/postcss-load-config + +module.exports = { + "plugins": { + // to edit target browsers: use "browserlist" field in package.json + "autoprefixer": {} + } +} diff --git a/front-end-tdd/README.md b/front-end-tdd/README.md new file mode 100644 index 0000000..218341a --- /dev/null +++ b/front-end-tdd/README.md @@ -0,0 +1,30 @@ +# front-end-tdd + +> A Vue.js project + +## Build Setup + +``` bash +# install dependencies +npm install + +# serve with hot reload at localhost:8080 +npm run dev + +# build for production with minification +npm run build + +# build for production and view the bundle analyzer report +npm run build --report + +# run unit tests +npm run unit + +# run e2e tests +npm run e2e + +# run all tests +npm test +``` + +For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader). diff --git a/front-end-tdd/build/build.js b/front-end-tdd/build/build.js new file mode 100644 index 0000000..6b8add1 --- /dev/null +++ b/front-end-tdd/build/build.js @@ -0,0 +1,35 @@ +require('./check-versions')() + +process.env.NODE_ENV = 'production' + +var ora = require('ora') +var rm = require('rimraf') +var path = require('path') +var chalk = require('chalk') +var webpack = require('webpack') +var config = require('../config') +var webpackConfig = require('./webpack.prod.conf') + +var spinner = ora('building for production...') +spinner.start() + +rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { + if (err) throw err + 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\n') + + console.log(chalk.cyan(' Build complete.\n')) + console.log(chalk.yellow( + ' Tip: built files are meant to be served over an HTTP server.\n' + + ' Opening index.html over file:// won\'t work.\n' + )) + }) +}) diff --git a/front-end-tdd/build/check-versions.js b/front-end-tdd/build/check-versions.js new file mode 100644 index 0000000..100f3a0 --- /dev/null +++ b/front-end-tdd/build/check-versions.js @@ -0,0 +1,48 @@ +var chalk = require('chalk') +var semver = require('semver') +var packageConfig = require('../package.json') +var shell = require('shelljs') +function exec (cmd) { + return require('child_process').execSync(cmd).toString().trim() +} + +var versionRequirements = [ + { + name: 'node', + currentVersion: semver.clean(process.version), + versionRequirement: packageConfig.engines.node + }, +] + +if (shell.which('npm')) { + versionRequirements.push({ + name: 'npm', + currentVersion: exec('npm --version'), + versionRequirement: packageConfig.engines.npm + }) +} + +module.exports = function () { + var warnings = [] + for (var i = 0; i < versionRequirements.length; i++) { + var mod = versionRequirements[i] + if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { + warnings.push(mod.name + ': ' + + chalk.red(mod.currentVersion) + ' should be ' + + chalk.green(mod.versionRequirement) + ) + } + } + + if (warnings.length) { + console.log('') + console.log(chalk.yellow('To use this template, you must update following to modules:')) + console.log() + for (var i = 0; i < warnings.length; i++) { + var warning = warnings[i] + console.log(' ' + warning) + } + console.log() + process.exit(1) + } +} diff --git a/front-end-tdd/build/dev-client.js b/front-end-tdd/build/dev-client.js new file mode 100644 index 0000000..18aa1e2 --- /dev/null +++ b/front-end-tdd/build/dev-client.js @@ -0,0 +1,9 @@ +/* eslint-disable */ +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/front-end-tdd/build/dev-server.js b/front-end-tdd/build/dev-server.js new file mode 100644 index 0000000..a048169 --- /dev/null +++ b/front-end-tdd/build/dev-server.js @@ -0,0 +1,91 @@ +require('./check-versions')() + +var config = require('../config') +if (!process.env.NODE_ENV) { + process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) +} + +var opn = require('opn') +var path = require('path') +var express = require('express') +var webpack = require('webpack') +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 +// automatically open browser, if not set will be false +var autoOpenBrowser = !!config.dev.autoOpenBrowser +// 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, + quiet: true +}) + +var hotMiddleware = require('webpack-hot-middleware')(compiler, { + log: () => {} +}) +// 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(options.filter || 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.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) +app.use(staticPath, express.static('./static')) + +var uri = 'http://localhost:' + port + +var _resolve +var readyPromise = new Promise(resolve => { + _resolve = resolve +}) + +console.log('> Starting dev server...') +devMiddleware.waitUntilValid(() => { + console.log('> Listening at ' + uri + '\n') + // when env is testing, don't need open it + if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { + opn(uri) + } + _resolve() +}) + +var server = app.listen(port) + +module.exports = { + ready: readyPromise, + close: () => { + server.close() + } +} diff --git a/front-end-tdd/build/utils.js b/front-end-tdd/build/utils.js new file mode 100644 index 0000000..b1d54b4 --- /dev/null +++ b/front-end-tdd/build/utils.js @@ -0,0 +1,71 @@ +var path = require('path') +var config = require('../config') +var ExtractTextPlugin = require('extract-text-webpack-plugin') + +exports.assetsPath = function (_path) { + var assetsSubDirectory = process.env.NODE_ENV === 'production' + ? config.build.assetsSubDirectory + : config.dev.assetsSubDirectory + return path.posix.join(assetsSubDirectory, _path) +} + +exports.cssLoaders = function (options) { + options = options || {} + + var cssLoader = { + loader: 'css-loader', + options: { + minimize: process.env.NODE_ENV === 'production', + sourceMap: options.sourceMap + } + } + + // generate loader string to be used with extract text plugin + function generateLoaders (loader, loaderOptions) { + var loaders = [cssLoader] + if (loader) { + loaders.push({ + loader: loader + '-loader', + options: Object.assign({}, loaderOptions, { + sourceMap: options.sourceMap + }) + }) + } + + // Extract CSS when that option is specified + // (which is the case during production build) + if (options.extract) { + return ExtractTextPlugin.extract({ + use: loaders, + fallback: 'vue-style-loader' + }) + } else { + return ['vue-style-loader'].concat(loaders) + } + } + + // https://vue-loader.vuejs.org/en/configurations/extract-css.html + return { + css: generateLoaders(), + postcss: generateLoaders(), + less: generateLoaders('less'), + sass: generateLoaders('sass', { indentedSyntax: true }), + scss: generateLoaders('sass'), + stylus: generateLoaders('stylus'), + styl: generateLoaders('stylus') + } +} + +// Generate loaders for standalone style files (outside of .vue) +exports.styleLoaders = function (options) { + var output = [] + var loaders = exports.cssLoaders(options) + for (var extension in loaders) { + var loader = loaders[extension] + output.push({ + test: new RegExp('\\.' + extension + '$'), + use: loader + }) + } + return output +} diff --git a/front-end-tdd/build/vue-loader.conf.js b/front-end-tdd/build/vue-loader.conf.js new file mode 100644 index 0000000..7aee79b --- /dev/null +++ b/front-end-tdd/build/vue-loader.conf.js @@ -0,0 +1,12 @@ +var utils = require('./utils') +var config = require('../config') +var isProduction = process.env.NODE_ENV === 'production' + +module.exports = { + loaders: utils.cssLoaders({ + sourceMap: isProduction + ? config.build.productionSourceMap + : config.dev.cssSourceMap, + extract: isProduction + }) +} diff --git a/front-end-tdd/build/webpack.base.conf.js b/front-end-tdd/build/webpack.base.conf.js new file mode 100644 index 0000000..f47b326 --- /dev/null +++ b/front-end-tdd/build/webpack.base.conf.js @@ -0,0 +1,67 @@ +var path = require('path') +var utils = require('./utils') +var config = require('../config') +var vueLoaderConfig = require('./vue-loader.conf') + +function resolve (dir) { + return path.join(__dirname, '..', dir) +} + +module.exports = { + entry: { + app: './src/main.js' + }, + output: { + path: config.build.assetsRoot, + filename: '[name].js', + publicPath: process.env.NODE_ENV === 'production' + ? config.build.assetsPublicPath + : config.dev.assetsPublicPath + }, + resolve: { + extensions: ['.js', '.vue', '.json'], + alias: { + 'vue$': 'vue/dist/vue.esm.js', + '@': resolve('src') + } + }, + module: { + rules: [ + { + test: /\.(js|vue)$/, + loader: 'eslint-loader', + enforce: 'pre', + include: [resolve('src'), resolve('test')], + options: { + formatter: require('eslint-friendly-formatter') + } + }, + { + test: /\.vue$/, + loader: 'vue-loader', + options: vueLoaderConfig + }, + { + test: /\.js$/, + loader: 'babel-loader', + include: [resolve('src'), resolve('test')] + }, + { + test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, + loader: 'url-loader', + options: { + limit: 10000, + name: utils.assetsPath('img/[name].[hash:7].[ext]') + } + }, + { + test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, + loader: 'url-loader', + options: { + limit: 10000, + name: utils.assetsPath('fonts/[name].[hash:7].[ext]') + } + } + ] + } +} diff --git a/front-end-tdd/build/webpack.dev.conf.js b/front-end-tdd/build/webpack.dev.conf.js new file mode 100644 index 0000000..5470402 --- /dev/null +++ b/front-end-tdd/build/webpack.dev.conf.js @@ -0,0 +1,35 @@ +var utils = require('./utils') +var webpack = require('webpack') +var config = require('../config') +var merge = require('webpack-merge') +var baseWebpackConfig = require('./webpack.base.conf') +var HtmlWebpackPlugin = require('html-webpack-plugin') +var FriendlyErrorsPlugin = require('friendly-errors-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, { + module: { + rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) + }, + // cheap-module-eval-source-map is faster for development + devtool: '#cheap-module-eval-source-map', + plugins: [ + new webpack.DefinePlugin({ + 'process.env': config.dev.env + }), + // https://github.com/glenjamin/webpack-hot-middleware#installation--usage + new webpack.HotModuleReplacementPlugin(), + new webpack.NoEmitOnErrorsPlugin(), + // https://github.com/ampedandwired/html-webpack-plugin + new HtmlWebpackPlugin({ + filename: 'index.html', + template: 'index.html', + inject: true + }), + new FriendlyErrorsPlugin() + ] +}) diff --git a/front-end-tdd/build/webpack.prod.conf.js b/front-end-tdd/build/webpack.prod.conf.js new file mode 100644 index 0000000..99713cc --- /dev/null +++ b/front-end-tdd/build/webpack.prod.conf.js @@ -0,0 +1,124 @@ +var path = require('path') +var utils = require('./utils') +var webpack = require('webpack') +var config = require('../config') +var merge = require('webpack-merge') +var baseWebpackConfig = require('./webpack.base.conf') +var CopyWebpackPlugin = require('copy-webpack-plugin') +var HtmlWebpackPlugin = require('html-webpack-plugin') +var ExtractTextPlugin = require('extract-text-webpack-plugin') +var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') + +var env = process.env.NODE_ENV === 'testing' + ? require('../config/test.env') + : config.build.env + +var webpackConfig = merge(baseWebpackConfig, { + module: { + rules: utils.styleLoaders({ + sourceMap: config.build.productionSourceMap, + extract: true + }) + }, + devtool: config.build.productionSourceMap ? '#source-map' : false, + output: { + path: config.build.assetsRoot, + filename: utils.assetsPath('js/[name].[chunkhash].js'), + chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') + }, + plugins: [ + // http://vuejs.github.io/vue-loader/en/workflow/production.html + new webpack.DefinePlugin({ + 'process.env': env + }), + new webpack.optimize.UglifyJsPlugin({ + compress: { + warnings: false + }, + sourceMap: true + }), + // extract css into its own file + new ExtractTextPlugin({ + filename: utils.assetsPath('css/[name].[contenthash].css') + }), + // Compress extracted CSS. We are using this plugin so that possible + // duplicated CSS from different components can be deduped. + new OptimizeCSSPlugin({ + cssProcessorOptions: { + safe: true + } + }), + // 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 + }, + // necessary to consistently work with multiple chunks via CommonsChunkPlugin + chunksSortMode: 'dependency' + }), + // split vendor js into its own file + new webpack.optimize.CommonsChunkPlugin({ + name: 'vendor', + minChunks: function (module, count) { + // any required modules inside node_modules are extracted to vendor + return ( + module.resource && + /\.js$/.test(module.resource) && + module.resource.indexOf( + path.join(__dirname, '../node_modules') + ) === 0 + ) + } + }), + // extract webpack runtime and module manifest to its own file in order to + // prevent vendor hash from being updated whenever app bundle is updated + new webpack.optimize.CommonsChunkPlugin({ + name: 'manifest', + chunks: ['vendor'] + }), + // copy custom static assets + new CopyWebpackPlugin([ + { + from: path.resolve(__dirname, '../static'), + to: config.build.assetsSubDirectory, + ignore: ['.*'] + } + ]) + ] +}) + +if (config.build.productionGzip) { + var CompressionWebpackPlugin = require('compression-webpack-plugin') + + webpackConfig.plugins.push( + new CompressionWebpackPlugin({ + asset: '[path].gz[query]', + algorithm: 'gzip', + test: new RegExp( + '\\.(' + + config.build.productionGzipExtensions.join('|') + + ')$' + ), + threshold: 10240, + minRatio: 0.8 + }) + ) +} + +if (config.build.bundleAnalyzerReport) { + var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin + webpackConfig.plugins.push(new BundleAnalyzerPlugin()) +} + +module.exports = webpackConfig diff --git a/front-end-tdd/build/webpack.test.conf.js b/front-end-tdd/build/webpack.test.conf.js new file mode 100644 index 0000000..d6c8c8d --- /dev/null +++ b/front-end-tdd/build/webpack.test.conf.js @@ -0,0 +1,31 @@ +// This is the webpack config used for unit tests. + +var utils = require('./utils') +var webpack = require('webpack') +var merge = require('webpack-merge') +var baseConfig = require('./webpack.base.conf') + +var webpackConfig = merge(baseConfig, { + // use inline sourcemap for karma-sourcemap-loader + module: { + rules: utils.styleLoaders() + }, + devtool: '#inline-source-map', + resolveLoader: { + alias: { + // necessary to to make lang="scss" work in test when using vue-loader's ?inject option + // see discussion at https://github.com/vuejs/vue-loader/issues/724 + 'scss-loader': 'sass-loader' + } + }, + plugins: [ + new webpack.DefinePlugin({ + 'process.env': require('../config/test.env') + }) + ] +}) + +// no need for app entry during tests +delete webpackConfig.entry + +module.exports = webpackConfig diff --git a/front-end-tdd/config/dev.env.js b/front-end-tdd/config/dev.env.js new file mode 100644 index 0000000..efead7c --- /dev/null +++ b/front-end-tdd/config/dev.env.js @@ -0,0 +1,6 @@ +var merge = require('webpack-merge') +var prodEnv = require('./prod.env') + +module.exports = merge(prodEnv, { + NODE_ENV: '"development"' +}) diff --git a/front-end-tdd/config/index.js b/front-end-tdd/config/index.js new file mode 100644 index 0000000..196da1f --- /dev/null +++ b/front-end-tdd/config/index.js @@ -0,0 +1,38 @@ +// see http://vuejs-templates.github.io/webpack for documentation. +var path = require('path') + +module.exports = { + build: { + env: require('./prod.env'), + index: path.resolve(__dirname, '../dist/index.html'), + assetsRoot: path.resolve(__dirname, '../dist'), + assetsSubDirectory: 'static', + assetsPublicPath: '/', + productionSourceMap: true, + // Gzip off by default as many popular static hosts such as + // Surge or Netlify already gzip all static assets for you. + // Before setting to `true`, make sure to: + // npm install --save-dev compression-webpack-plugin + productionGzip: false, + productionGzipExtensions: ['js', 'css'], + // Run the build command with an extra argument to + // View the bundle analyzer report after build finishes: + // `npm run build --report` + // Set to `true` or `false` to always turn it on or off + bundleAnalyzerReport: process.env.npm_config_report + }, + dev: { + env: require('./dev.env'), + port: 8080, + autoOpenBrowser: true, + assetsSubDirectory: 'static', + assetsPublicPath: '/', + proxyTable: {}, + // CSS Sourcemaps off by default because relative paths are "buggy" + // with this option, according to the CSS-Loader README + // (https://github.com/webpack/css-loader#sourcemaps) + // In our experience, they generally work as expected, + // just be aware of this issue when enabling this option. + cssSourceMap: false + } +} diff --git a/front-end-tdd/config/prod.env.js b/front-end-tdd/config/prod.env.js new file mode 100644 index 0000000..773d263 --- /dev/null +++ b/front-end-tdd/config/prod.env.js @@ -0,0 +1,3 @@ +module.exports = { + NODE_ENV: '"production"' +} diff --git a/front-end-tdd/config/test.env.js b/front-end-tdd/config/test.env.js new file mode 100644 index 0000000..89f90de --- /dev/null +++ b/front-end-tdd/config/test.env.js @@ -0,0 +1,6 @@ +var merge = require('webpack-merge') +var devEnv = require('./dev.env') + +module.exports = merge(devEnv, { + NODE_ENV: '"testing"' +}) diff --git a/front-end-tdd/index.html b/front-end-tdd/index.html new file mode 100644 index 0000000..5553bd6 --- /dev/null +++ b/front-end-tdd/index.html @@ -0,0 +1,15 @@ + + + + + front-end-tdd + + + + + + +
+ + + diff --git a/front-end-tdd/package.json b/front-end-tdd/package.json new file mode 100644 index 0000000..8ed4a8f --- /dev/null +++ b/front-end-tdd/package.json @@ -0,0 +1,95 @@ +{ + "name": "front-end-tdd", + "version": "1.0.0", + "description": "A Vue.js project", + "author": "Antoni Angga ", + "private": true, + "scripts": { + "dev": "node build/dev-server.js", + "start": "node build/dev-server.js", + "build": "node build/build.js", + "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run", + "e2e": "node test/e2e/runner.js", + "test": "npm run unit && npm run e2e", + "lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs" + }, + "dependencies": { + "axios": "^0.16.2", + "vue": "^2.3.3", + "vue-router": "^2.3.1" + }, + "devDependencies": { + "autoprefixer": "^6.7.2", + "babel-core": "^6.22.1", + "babel-eslint": "^7.1.1", + "babel-loader": "^6.2.10", + "babel-plugin-transform-runtime": "^6.22.0", + "babel-preset-env": "^1.3.2", + "babel-preset-stage-2": "^6.22.0", + "babel-register": "^6.22.0", + "chalk": "^1.1.3", + "connect-history-api-fallback": "^1.3.0", + "copy-webpack-plugin": "^4.0.1", + "css-loader": "^0.28.0", + "eslint": "^3.19.0", + "eslint-friendly-formatter": "^2.0.7", + "eslint-loader": "^1.7.1", + "eslint-plugin-html": "^2.0.0", + "eslint-config-standard": "^6.2.1", + "eslint-plugin-promise": "^3.4.0", + "eslint-plugin-standard": "^2.0.1", + "eventsource-polyfill": "^0.9.6", + "express": "^4.14.1", + "extract-text-webpack-plugin": "^2.0.0", + "file-loader": "^0.11.1", + "friendly-errors-webpack-plugin": "^1.1.3", + "html-webpack-plugin": "^2.28.0", + "http-proxy-middleware": "^0.17.3", + "webpack-bundle-analyzer": "^2.2.1", + "cross-env": "^4.0.0", + "karma": "^1.4.1", + "karma-coverage": "^1.1.1", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-phantomjs-shim": "^1.4.0", + "karma-sinon-chai": "^1.3.1", + "karma-sourcemap-loader": "^0.3.7", + "karma-spec-reporter": "0.0.30", + "karma-webpack": "^2.0.2", + "lolex": "^1.5.2", + "mocha": "^3.2.0", + "chai": "^3.5.0", + "sinon": "^2.1.0", + "sinon-chai": "^2.8.0", + "inject-loader": "^3.0.0", + "babel-plugin-istanbul": "^4.1.1", + "phantomjs-prebuilt": "^2.1.14", + "chromedriver": "^2.27.2", + "cross-spawn": "^5.0.1", + "nightwatch": "^0.9.12", + "selenium-server": "^3.0.1", + "semver": "^5.3.0", + "shelljs": "^0.7.6", + "opn": "^4.0.2", + "optimize-css-assets-webpack-plugin": "^1.3.0", + "ora": "^1.2.0", + "rimraf": "^2.6.0", + "url-loader": "^0.5.8", + "vue-loader": "^12.1.0", + "vue-style-loader": "^3.0.1", + "vue-template-compiler": "^2.3.3", + "webpack": "^2.6.1", + "webpack-dev-middleware": "^1.10.0", + "webpack-hot-middleware": "^2.18.0", + "webpack-merge": "^4.1.0" + }, + "engines": { + "node": ">= 4.0.0", + "npm": ">= 3.0.0" + }, + "browserslist": [ + "> 1%", + "last 2 versions", + "not ie <= 8" + ] +} diff --git a/front-end-tdd/src/App.vue b/front-end-tdd/src/App.vue new file mode 100644 index 0000000..76bb961 --- /dev/null +++ b/front-end-tdd/src/App.vue @@ -0,0 +1,11 @@ + + + diff --git a/front-end-tdd/src/assets/logo.png b/front-end-tdd/src/assets/logo.png new file mode 100644 index 0000000..f3d2503 Binary files /dev/null and b/front-end-tdd/src/assets/logo.png differ diff --git a/front-end-tdd/src/components/Dashboard.vue b/front-end-tdd/src/components/Dashboard.vue new file mode 100644 index 0000000..9c336e9 --- /dev/null +++ b/front-end-tdd/src/components/Dashboard.vue @@ -0,0 +1,74 @@ + + + + + diff --git a/front-end-tdd/src/components/HalDashboard.vue b/front-end-tdd/src/components/HalDashboard.vue new file mode 100644 index 0000000..3293f63 --- /dev/null +++ b/front-end-tdd/src/components/HalDashboard.vue @@ -0,0 +1,8 @@ + + + diff --git a/front-end-tdd/src/components/Hello.vue b/front-end-tdd/src/components/Hello.vue new file mode 100644 index 0000000..1ffb79d --- /dev/null +++ b/front-end-tdd/src/components/Hello.vue @@ -0,0 +1,55 @@ + + + + + + diff --git a/front-end-tdd/src/components/MainDashboard.vue b/front-end-tdd/src/components/MainDashboard.vue new file mode 100644 index 0000000..d18900a --- /dev/null +++ b/front-end-tdd/src/components/MainDashboard.vue @@ -0,0 +1,47 @@ + + + + + diff --git a/front-end-tdd/src/components/Template.vue b/front-end-tdd/src/components/Template.vue new file mode 100644 index 0000000..2e2c04b --- /dev/null +++ b/front-end-tdd/src/components/Template.vue @@ -0,0 +1,68 @@ + + + + + + diff --git a/front-end-tdd/src/main.js b/front-end-tdd/src/main.js new file mode 100644 index 0000000..a0d6bd3 --- /dev/null +++ b/front-end-tdd/src/main.js @@ -0,0 +1,17 @@ +// The Vue build version to load with the `import` command +// (runtime-only or standalone) has been set in webpack.base.conf with an alias. +import Vue from 'vue' +import App from './App' +import router from './router' +import axios from 'axios' + +Vue.config.productionTip = false +Vue.prototype.$http = axios + +/* eslint-disable no-new */ +new Vue({ + el: '#app', + router, + template: '', + components: { App } +}) diff --git a/front-end-tdd/src/router/index.js b/front-end-tdd/src/router/index.js new file mode 100644 index 0000000..a3784e3 --- /dev/null +++ b/front-end-tdd/src/router/index.js @@ -0,0 +1,34 @@ +import Vue from 'vue' +import Router from 'vue-router' +import Hello from '@/components/Hello' +import Dashboard from '@/components/Dashboard' +import MainDashboard from '@/components/MainDashboard' +import Template from '@/components/Template' + +Vue.use(Router) + +export default new Router({ + routes: [ + { + path: '/', + name: 'Hello', + component: Hello + }, + { + path: '/dashboard', + name: 'Dashboard', + component: Dashboard, + children: [ + { + path: '', + component: MainDashboard + }, + { + path: '/dashboard/:id', + component: Template, + props: true + } + ] + } + ] +}) diff --git a/front-end-tdd/static/.gitkeep b/front-end-tdd/static/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/front-end-tdd/test/e2e/custom-assertions/elementCount.js b/front-end-tdd/test/e2e/custom-assertions/elementCount.js new file mode 100644 index 0000000..c0d5fe0 --- /dev/null +++ b/front-end-tdd/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/front-end-tdd/test/e2e/nightwatch.conf.js b/front-end-tdd/test/e2e/nightwatch.conf.js new file mode 100644 index 0000000..f019c0a --- /dev/null +++ b/front-end-tdd/test/e2e/nightwatch.conf.js @@ -0,0 +1,46 @@ +require('babel-register') +var config = require('../../config') + +// http://nightwatchjs.org/gettingstarted#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: require('selenium-server').path, + 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, + globals: { + devServerURL: 'http://localhost:' + (process.env.PORT || config.dev.port) + } + }, + + chrome: { + desiredCapabilities: { + browserName: 'chrome', + javascriptEnabled: true, + acceptSslCerts: true + } + }, + + firefox: { + desiredCapabilities: { + browserName: 'firefox', + javascriptEnabled: true, + acceptSslCerts: true + } + } + } +} diff --git a/front-end-tdd/test/e2e/runner.js b/front-end-tdd/test/e2e/runner.js new file mode 100644 index 0000000..85d67d6 --- /dev/null +++ b/front-end-tdd/test/e2e/runner.js @@ -0,0 +1,33 @@ +// 1. start the dev server using production config +process.env.NODE_ENV = 'testing' +var server = require('../../build/dev-server.js') + +server.ready.then(() => { + // 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 + // or override the environment flag, for example: `npm run e2e -- --env chrome,firefox` + // For more information on Nightwatch's config file, see + // http://nightwatchjs.org/guide#settings-file + var opts = process.argv.slice(2) + if (opts.indexOf('--config') === -1) { + opts = opts.concat(['--config', 'test/e2e/nightwatch.conf.js']) + } + if (opts.indexOf('--env') === -1) { + opts = opts.concat(['--env', 'chrome']) + } + + var spawn = require('cross-spawn') + var runner = spawn('./node_modules/.bin/nightwatch', opts, { stdio: 'inherit' }) + + runner.on('exit', function (code) { + server.close() + process.exit(code) + }) + + runner.on('error', function (err) { + server.close() + throw err + }) +}) diff --git a/front-end-tdd/test/e2e/specs/test.js b/front-end-tdd/test/e2e/specs/test.js new file mode 100644 index 0000000..a7b1bd9 --- /dev/null +++ b/front-end-tdd/test/e2e/specs/test.js @@ -0,0 +1,19 @@ +// For authoring Nightwatch tests, see +// http://nightwatchjs.org/guide#usage + +module.exports = { + 'default e2e tests': function (browser) { + // automatically uses dev Server port from /config.index.js + // default: http://localhost:8080 + // see nightwatch.conf.js + const devServer = browser.globals.devServerURL + + browser + .url(devServer) + .waitForElementVisible('#app', 5000) + .assert.elementPresent('.hello') + .assert.containsText('h1', 'Welcome to Your Vue.js App') + .assert.elementCount('img', 1) + .end() + } +} diff --git a/front-end-tdd/test/unit/.eslintrc b/front-end-tdd/test/unit/.eslintrc new file mode 100644 index 0000000..959a4f4 --- /dev/null +++ b/front-end-tdd/test/unit/.eslintrc @@ -0,0 +1,9 @@ +{ + "env": { + "mocha": true + }, + "globals": { + "expect": true, + "sinon": true + } +} diff --git a/front-end-tdd/test/unit/index.js b/front-end-tdd/test/unit/index.js new file mode 100644 index 0000000..c69f33f --- /dev/null +++ b/front-end-tdd/test/unit/index.js @@ -0,0 +1,13 @@ +import Vue from 'vue' + +Vue.config.productionTip = false + +// require all test files (files that ends with .spec.js) +const 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. +const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/) +srcContext.keys().forEach(srcContext) diff --git a/front-end-tdd/test/unit/karma.conf.js b/front-end-tdd/test/unit/karma.conf.js new file mode 100644 index 0000000..8e4951c --- /dev/null +++ b/front-end-tdd/test/unit/karma.conf.js @@ -0,0 +1,33 @@ +// 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 webpackConfig = require('../../build/webpack.test.conf') + +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', 'phantomjs-shim'], + 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/front-end-tdd/test/unit/specs/Hello.spec.js b/front-end-tdd/test/unit/specs/Hello.spec.js new file mode 100644 index 0000000..80140ba --- /dev/null +++ b/front-end-tdd/test/unit/specs/Hello.spec.js @@ -0,0 +1,11 @@ +import Vue from 'vue' +import Hello from '@/components/Hello' + +describe('Hello.vue', () => { + it('should render correct contents', () => { + const Constructor = Vue.extend(Hello) + const vm = new Constructor().$mount() + expect(vm.$el.querySelector('.hello h1').textContent) + .to.equal('Welcome to Your Vue.js App') + }) +})