Tuesday 26 September 2017

Mocha Unit Testing Help

Hi All, Starting to learn node and although I've been programming in various languages for a while, unit testing has never been a priority (I know, I know...).I wrote the below code as part of a challenge the other day but couldn't determine a proper way of unit testing it. Would appreciate some guidance, thanks.const mysql = require('mysql'); const Sequelize = require('sequelize'); const host = process.env.DB_HOST || '127.0.0.1'; const user = process.env.DB_USER || 'root'; const password = process.env.DB_PASSWORD || 'root'; const db = process.env.DB_DATABASE || 'test'; //Use Sequelize to create models of our database and insert the initial values const sequelize = new Sequelize(db, user, password, {host: host, dialect: 'mysql'}); const SiteData = sequelize.define('site_data', { site_id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true }, power: Sequelize.INTEGER, dsu_id: Sequelize.INTEGER },{ timestamps:false }); const DsuData = sequelize.define('dsu_data', { dsu_id: { type: Sequelize.INTEGER, primaryKey: true }, total_power: Sequelize.INTEGER },{ timestamps:false }); //force flag on sync function will drop the tables if they exist and then recreate them DsuData.sync({force: true}); //write initial data to SiteData model, once it is created, call insert function ona 1 second interval SiteData.sync({force: true}) .then(() => SiteData.create({ power: 234, dsu_id: 1 })) .then(() => SiteData.create({ power: 443, dsu_id: 1 })) .then(() => SiteData.create({ power: 232, dsu_id: 1 })) .then(() => SiteData.create({ power: 111, dsu_id: 2 })) .then(() => { setInterval(insert,1000); }); //Query database for all distinct dsu_id, and aggregates of their powers -select dsu_id, sum(power) as 'total' from site_data group by dsu_id; //For each row in resulting array, call upsert function const insert = () => { SiteData.findAll({ group: ['dsu_id'], attributes: ['dsu_id',[Sequelize.fn('SUM',Sequelize.col('power')),'total']] }) .then((siteDatas) => { siteDatas.forEach(function (arrayitem) { upsert({ dsu_id: arrayitem.dsu_id,total_power: arrayitem.get('total') },{dsu_id:arrayitem.dsu_id }).then(function(result){ }); }); }); }; //if row exists with matching dsu_id, update the total_power value //if it doesn't exist, insert the dsu_id and total_power function upsert(values, condition) { return DsuData .findOne({ where: condition }) .then(function(obj) { if(obj) { // update return obj.update(values); } else { // insert return DsuData.create(values); } }) }

Submitted September 26, 2017 at 08:25AM by AlphabetHat

No comments:

Post a Comment