unit tests

This commit is contained in:
Karsten Hassel 2021-06-06 23:13:09 +02:00
parent 32df76bdff
commit 66759a33fa
12 changed files with 78 additions and 50 deletions

View File

@ -22,7 +22,8 @@
root.Log = factory(root.config); root.Log = factory(root.config);
} }
})(this, function (config) { })(this, function (config) {
const logLevel = {
let logLevel = {
debug: Function.prototype.bind.call(console.debug, console), debug: Function.prototype.bind.call(console.debug, console),
log: Function.prototype.bind.call(console.log, console), log: Function.prototype.bind.call(console.log, console),
info: Function.prototype.bind.call(console.info, console), info: Function.prototype.bind.call(console.info, console),
@ -32,8 +33,11 @@
groupCollapsed: Function.prototype.bind.call(console.groupCollapsed, console), groupCollapsed: Function.prototype.bind.call(console.groupCollapsed, console),
groupEnd: Function.prototype.bind.call(console.groupEnd, console), groupEnd: Function.prototype.bind.call(console.groupEnd, console),
time: Function.prototype.bind.call(console.time, console), time: Function.prototype.bind.call(console.time, console),
timeEnd: Function.prototype.bind.call(console.timeEnd, console), timeEnd: Function.prototype.bind.call(console.timeEnd, console)
timeStamp: Function.prototype.bind.call(console.timeStamp, console) };
if (process.env.NODE_ENV.trim() !== "test") {
logLevel.push({timeStamp: Function.prototype.bind.call(console.timeStamp, console)});
}; };
logLevel.setLogLevel = function (newLevel) { logLevel.setLogLevel = function (newLevel) {

View File

@ -339,7 +339,9 @@ Module.register("weatherforecast", {
* *
* argument data object - Weather information received form openweather.org. * argument data object - Weather information received form openweather.org.
*/ */
processWeather: function (data) { processWeather: function (data, momenttz) {
let mom;
if (momenttz === null) {mom = moment} else {mom = momenttz};
// Forcast16 (paid) API endpoint provides this data. Onecall endpoint // Forcast16 (paid) API endpoint provides this data. Onecall endpoint
// does not. // does not.
if (data.city) { if (data.city) {
@ -357,8 +359,8 @@ Module.register("weatherforecast", {
var dayEnds = 17; var dayEnds = 17;
if (data.city && data.city.sunrise && data.city.sunset) { if (data.city && data.city.sunrise && data.city.sunset) {
dayStarts = new Date(moment.unix(data.city.sunrise).locale("en").format("YYYY/MM/DD HH:mm:ss")).getHours(); dayStarts = new Date(mom.unix(data.city.sunrise).locale("en").format("YYYY/MM/DD HH:mm:ss")).getHours();
dayEnds = new Date(moment.unix(data.city.sunset).locale("en").format("YYYY/MM/DD HH:mm:ss")).getHours(); dayEnds = new Date(mom.unix(data.city.sunset).locale("en").format("YYYY/MM/DD HH:mm:ss")).getHours();
} }
// Handle different structs between forecast16 and onecall endpoints // Handle different structs between forecast16 and onecall endpoints
@ -379,11 +381,11 @@ Module.register("weatherforecast", {
var day; var day;
var hour; var hour;
if (forecast.dt_txt) { if (forecast.dt_txt) {
day = moment(forecast.dt_txt, "YYYY-MM-DD hh:mm:ss").format("ddd"); day = mom(forecast.dt_txt, "YYYY-MM-DD hh:mm:ss").format("ddd");
hour = new Date(moment(forecast.dt_txt).locale("en").format("YYYY-MM-DD HH:mm:ss")).getHours(); hour = new Date(mom(forecast.dt_txt).locale("en").format("YYYY-MM-DD HH:mm:ss")).getHours();
} else { } else {
day = moment(forecast.dt, "X").format("ddd"); day = mom(forecast.dt, "X").format("ddd");
hour = new Date(moment(forecast.dt, "X")).getHours(); hour = new Date(mom(forecast.dt, "X")).getHours();
} }
if (day !== lastDay) { if (day !== lastDay) {
@ -392,7 +394,7 @@ Module.register("weatherforecast", {
icon: this.config.iconTable[forecast.weather[0].icon], icon: this.config.iconTable[forecast.weather[0].icon],
maxTemp: this.roundValue(forecast.temp.max), maxTemp: this.roundValue(forecast.temp.max),
minTemp: this.roundValue(forecast.temp.min), minTemp: this.roundValue(forecast.temp.min),
rain: this.processRain(forecast, forecastList) rain: this.processRain(forecast, forecastList, mom)
}; };
this.forecast.push(forecastData); this.forecast.push(forecastData);
lastDay = day; lastDay = day;
@ -482,16 +484,18 @@ Module.register("weatherforecast", {
* That object has a property "3h" which contains the amount of rain since the previous forecast in the list. * That object has a property "3h" which contains the amount of rain since the previous forecast in the list.
* This code finds all forecasts that is for the same day and sums the amount of rain and returns that. * This code finds all forecasts that is for the same day and sums the amount of rain and returns that.
*/ */
processRain: function (forecast, allForecasts) { processRain: function (forecast, allForecasts, momenttz) {
let mom;
if (momenttz === null) {mom = moment} else {mom = momenttz};
//If the amount of rain actually is a number, return it //If the amount of rain actually is a number, return it
if (!isNaN(forecast.rain)) { if (!isNaN(forecast.rain)) {
return forecast.rain; return forecast.rain;
} }
//Find all forecasts that is for the same day //Find all forecasts that is for the same day
var checkDateTime = forecast.dt_txt ? moment(forecast.dt_txt, "YYYY-MM-DD hh:mm:ss") : moment(forecast.dt, "X"); var checkDateTime = forecast.dt_txt ? mom(forecast.dt_txt, "YYYY-MM-DD hh:mm:ss") : mom(forecast.dt, "X");
var daysForecasts = allForecasts.filter(function (item) { var daysForecasts = allForecasts.filter(function (item) {
var itemDateTime = item.dt_txt ? moment(item.dt_txt, "YYYY-MM-DD hh:mm:ss") : moment(item.dt, "X"); var itemDateTime = item.dt_txt ? mom(item.dt_txt, "YYYY-MM-DD hh:mm:ss") : mom(item.dt, "X");
return itemDateTime.isSame(checkDateTime, "day") && item.rain instanceof Object; return itemDateTime.isSame(checkDateTime, "day") && item.rain instanceof Object;
}); });

View File

@ -13,7 +13,7 @@
"test": "NODE_ENV=test mocha tests --recursive", "test": "NODE_ENV=test mocha tests --recursive",
"test:coverage": "NODE_ENV=test nyc --reporter=lcov --reporter=text mocha tests --recursive --timeout=3000", "test:coverage": "NODE_ENV=test nyc --reporter=lcov --reporter=text mocha tests --recursive --timeout=3000",
"test:e2e": "NODE_ENV=test mocha tests/e2e --recursive", "test:e2e": "NODE_ENV=test mocha tests/e2e --recursive",
"test:unit": "NODE_ENV=test mocha tests/unit --recursive", "test:unit": "NODE_ENV=test jest --testMatch **/tests/unit/**/*",
"test:prettier": "prettier . --check", "test:prettier": "prettier . --check",
"test:js": "eslint js/**/*.js modules/default/**/*.js clientonly/*.js serveronly/*.js translations/*.js vendor/*.js tests/**/*.js config/* --config .eslintrc.json --quiet", "test:js": "eslint js/**/*.js modules/default/**/*.js clientonly/*.js serveronly/*.js translations/*.js vendor/*.js tests/**/*.js config/* --config .eslintrc.json --quiet",
"test:css": "stylelint css/main.css modules/default/**/*.css --config .stylelintrc.json", "test:css": "stylelint css/main.css modules/default/**/*.css --config .stylelintrc.json",
@ -52,11 +52,9 @@
"eslint-plugin-prettier": "^3.4.0", "eslint-plugin-prettier": "^3.4.0",
"express-basic-auth": "^1.2.0", "express-basic-auth": "^1.2.0",
"husky": "^6.0.0", "husky": "^6.0.0",
"jest": "27.0.4",
"jsdom": "^16.6.0", "jsdom": "^16.6.0",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"mocha": "^8.4.0",
"mocha-each": "^2.0.1",
"mocha-logger": "^1.0.7",
"nyc": "^15.1.0", "nyc": "^15.1.0",
"prettier": "^2.3.0", "prettier": "^2.3.0",
"pretty-quick": "^3.1.0", "pretty-quick": "^3.1.0",
@ -93,5 +91,13 @@
}, },
"engines": { "engines": {
"node": ">=12" "node": ">=12"
},
"jest": {
"moduleNameMapper": {
"node_helper": "<rootDir>/js/node_helper.js",
"logger": "<rootDir>/js/logger.js",
"moment-timezone": "<rootDir>/node_modules/moment-timezone/moment-timezone.js",
"moment": "<rootDir>/node_modules/moment/moment.js"
}
} }
} }

View File

@ -7,7 +7,7 @@ describe("File js/class", function () {
let clone; let clone;
let dom; let dom;
before(function (done) { beforeAll(function (done) {
dom = new JSDOM( dom = new JSDOM(
`<script>var Log = {log: function() {}};</script>\ `<script>var Log = {log: function() {}};</script>\
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "class.js")}">`, <script src="file://${path.join(__dirname, "..", "..", "..", "js", "class.js")}">`,
@ -87,14 +87,14 @@ describe("File js/class", function () {
describe("Test lockstring code", function () { describe("Test lockstring code", function () {
let log; let log;
before(function () { beforeAll(function () {
log = dom.window.Log.log; log = dom.window.Log.log;
dom.window.Log.log = function cmp(str) { dom.window.Log.log = function cmp(str) {
expect(str).to.equal("lockStrings"); expect(str).to.equal("lockStrings");
}; };
}); });
after(function () { afterAll(function () {
dom.window.Log.log = log; dom.window.Log.log = log;
}); });

View File

@ -3,11 +3,12 @@ const path = require("path");
const helmet = require("helmet"); const helmet = require("helmet");
const { JSDOM } = require("jsdom"); const { JSDOM } = require("jsdom");
const express = require("express"); const express = require("express");
const sockets = new Set();
describe("Translator", function () { describe("Translator", function () {
let server; let server;
before(function () { beforeAll(function () {
const app = express(); const app = express();
app.use(helmet()); app.use(helmet());
app.use(function (req, res, next) { app.use(function (req, res, next) {
@ -17,9 +18,20 @@ describe("Translator", function () {
app.use("/translations", express.static(path.join(__dirname, "..", "..", "..", "tests", "configs", "data"))); app.use("/translations", express.static(path.join(__dirname, "..", "..", "..", "tests", "configs", "data")));
server = app.listen(3000); server = app.listen(3000);
server.on('connection', (socket) => {
sockets.add(socket);
});
}); });
after(function () { afterAll(function () {
for (const socket of sockets) {
socket.destroy();
sockets.delete(socket);
}
server.close(); server.close();
}); });

View File

@ -10,7 +10,7 @@ describe("Functions into modules/default/calendar/calendar.js", function () {
Module.definitions[name] = moduleDefinition; Module.definitions[name] = moduleDefinition;
}; };
before(function () { beforeAll(function () {
// load calendar.js // load calendar.js
require("../../../modules/default/calendar/calendar.js"); require("../../../modules/default/calendar/calendar.js");
}); });

View File

@ -5,7 +5,7 @@ const { JSDOM } = require("jsdom");
describe("Test function cmpVersions in js/module.js", function () { describe("Test function cmpVersions in js/module.js", function () {
let cmp; let cmp;
before(function (done) { beforeAll(function (done) {
const dom = new JSDOM( const dom = new JSDOM(
`<script>var Class = {extend: function() { return {}; }};</script>\ `<script>var Class = {extend: function() { return {}; }};</script>\
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "module.js")}">`, <script src="file://${path.join(__dirname, "..", "..", "..", "js", "module.js")}">`,

View File

@ -10,14 +10,14 @@ describe("Functions module currentweather", function () {
Module.definitions[name] = moduleDefinition; Module.definitions[name] = moduleDefinition;
}; };
before(function () { beforeAll(function () {
require("../../../modules/default/currentweather/currentweather.js"); require("../../../modules/default/currentweather/currentweather.js");
Module.definitions.currentweather.config = {}; Module.definitions.currentweather.config = {};
}); });
describe("roundValue", function () { describe("roundValue", function () {
describe("this.config.roundTemp is true", function () { describe("this.config.roundTemp is true", function () {
before(function () { beforeAll(function () {
Module.definitions.currentweather.config.roundTemp = true; Module.definitions.currentweather.config.roundTemp = true;
}); });
@ -41,7 +41,7 @@ describe("Functions module currentweather", function () {
}); });
describe("this.config.roundTemp is false", function () { describe("this.config.roundTemp is false", function () {
before(function () { beforeAll(function () {
Module.definitions.currentweather.config.roundTemp = false; Module.definitions.currentweather.config.roundTemp = false;
}); });

View File

@ -8,8 +8,10 @@ describe("Functions into modules/default/newsfeed/newsfeed.js", function () {
Module.definitions[name] = moduleDefinition; Module.definitions[name] = moduleDefinition;
}; };
before(function () { beforeAll(function () {
// load newsfeed.js // load newsfeed.js
require("../../../modules/default/newsfeed/newsfeed.js"); require("../../../modules/default/newsfeed/newsfeed.js");
}); });
test.skip('skip', () => {});
}); });

View File

@ -4,7 +4,7 @@ const moment = require("moment-timezone");
const data = require("../../configs/data/weatherforecast_data.json"); const data = require("../../configs/data/weatherforecast_data.json");
describe("Functions module weatherforecast", function () { describe("Functions module weatherforecast", function () {
before(function () { beforeAll(function () {
Module = {}; Module = {};
config = {}; config = {};
Module.definitions = {}; Module.definitions = {};
@ -17,7 +17,7 @@ describe("Functions module weatherforecast", function () {
describe("roundValue", function () { describe("roundValue", function () {
describe("this.config.roundTemp is true", function () { describe("this.config.roundTemp is true", function () {
before(function () { beforeAll(function () {
Module.definitions.weatherforecast.config.roundTemp = true; Module.definitions.weatherforecast.config.roundTemp = true;
}); });
@ -41,7 +41,7 @@ describe("Functions module weatherforecast", function () {
}); });
describe("this.config.roundTemp is false", function () { describe("this.config.roundTemp is false", function () {
before(function () { beforeAll(function () {
Module.definitions.weatherforecast.config.roundTemp = false; Module.definitions.weatherforecast.config.roundTemp = false;
}); });
@ -73,7 +73,7 @@ describe("Functions module weatherforecast", function () {
let originalLocale; let originalLocale;
let originalTimeZone; let originalTimeZone;
before(function () { beforeAll(function () {
originalLocale = moment.locale(); originalLocale = moment.locale();
originalTimeZone = moment.tz.guess(); originalTimeZone = moment.tz.guess();
moment.locale("hi"); moment.locale("hi");
@ -81,7 +81,7 @@ describe("Functions module weatherforecast", function () {
}); });
describe("forecastIcons sunset specified", function () { describe("forecastIcons sunset specified", function () {
before(function () { beforeAll(function () {
Module.definitions.weatherforecast.Log = {}; Module.definitions.weatherforecast.Log = {};
Module.definitions.weatherforecast.forecast = []; Module.definitions.weatherforecast.forecast = [];
Module.definitions.weatherforecast.show = Module.definitions.weatherforecast.updateDom = function () {}; Module.definitions.weatherforecast.show = Module.definitions.weatherforecast.updateDom = function () {};
@ -89,7 +89,7 @@ describe("Functions module weatherforecast", function () {
}); });
it(`returns correct icons with sunset time`, function () { it(`returns correct icons with sunset time`, function () {
Module.definitions.weatherforecast.processWeather(data.withSunset); Module.definitions.weatherforecast.processWeather(data.withSunset, moment);
let forecastData = Module.definitions.weatherforecast.forecast; let forecastData = Module.definitions.weatherforecast.forecast;
expect(forecastData.length).to.equal(4); expect(forecastData.length).to.equal(4);
expect(forecastData[2].icon).to.equal("wi-rain"); expect(forecastData[2].icon).to.equal("wi-rain");
@ -97,19 +97,19 @@ describe("Functions module weatherforecast", function () {
}); });
describe("forecastIcons sunset not specified", function () { describe("forecastIcons sunset not specified", function () {
before(function () { beforeAll(function () {
Module.definitions.weatherforecast.forecast = []; Module.definitions.weatherforecast.forecast = [];
}); });
it(`returns correct icons with out sunset time`, function () { it(`returns correct icons with out sunset time`, function () {
Module.definitions.weatherforecast.processWeather(data.withoutSunset); Module.definitions.weatherforecast.processWeather(data.withoutSunset, moment);
let forecastData = Module.definitions.weatherforecast.forecast; let forecastData = Module.definitions.weatherforecast.forecast;
expect(forecastData.length).to.equal(4); expect(forecastData.length).to.equal(4);
expect(forecastData[2].icon).to.equal("wi-rain"); expect(forecastData[2].icon).to.equal("wi-rain");
}); });
}); });
after(function () { afterAll(function () {
moment.locale(originalLocale); moment.locale(originalLocale);
moment.tz.setDefault(originalTimeZone); moment.tz.setDefault(originalTimeZone);
}); });

View File

@ -5,12 +5,12 @@ const vm = require("vm");
const basedir = path.join(__dirname, "../../.."); const basedir = path.join(__dirname, "../../..");
before(function () { beforeAll(function () {
const fileName = "js/app.js"; const fileName = "js/app.js";
const filePath = path.join(basedir, fileName); const filePath = path.join(basedir, fileName);
const code = fs.readFileSync(filePath); const code = fs.readFileSync(filePath);
this.sandbox = { sandbox = {
module: {}, module: {},
__dirname: path.dirname(filePath), __dirname: path.dirname(filePath),
global: {}, global: {},
@ -27,13 +27,13 @@ before(function () {
} }
}; };
this.sandbox.require = function (filename) { sandbox.require = function (filename) {
// This modifies the global slightly, // This modifies the global slightly,
// but supplies vm with essential code // but supplies vm with essential code
return require(filename); return require(filename);
}; };
vm.runInNewContext(code, this.sandbox, fileName); vm.runInNewContext(code, sandbox, fileName);
}); });
describe("Default modules set in modules/default/defaultmodules.js", function () { describe("Default modules set in modules/default/defaultmodules.js", function () {
@ -41,7 +41,7 @@ describe("Default modules set in modules/default/defaultmodules.js", function ()
for (const defaultModule of expectedDefaultModules) { for (const defaultModule of expectedDefaultModules) {
it(`contains a folder for modules/default/${defaultModule}"`, function () { it(`contains a folder for modules/default/${defaultModule}"`, function () {
expect(fs.existsSync(path.join(this.sandbox.global.root_path, "modules/default", defaultModule))).to.equal(true); expect(fs.existsSync(path.join(sandbox.global.root_path, "modules/default", defaultModule))).to.equal(true);
}); });
} }
}); });

View File

@ -3,14 +3,14 @@ const path = require("path");
const expect = require("chai").expect; const expect = require("chai").expect;
const vm = require("vm"); const vm = require("vm");
before(function () { beforeAll(function () {
const basedir = path.join(__dirname, "../../.."); const basedir = path.join(__dirname, "../../..");
const fileName = "js/app.js"; const fileName = "js/app.js";
const filePath = path.join(basedir, fileName); const filePath = path.join(basedir, fileName);
const code = fs.readFileSync(filePath); const code = fs.readFileSync(filePath);
this.sandbox = { sandbox = {
module: {}, module: {},
__dirname: path.dirname(filePath), __dirname: path.dirname(filePath),
global: {}, global: {},
@ -27,16 +27,16 @@ before(function () {
} }
}; };
this.sandbox.require = function (filename) { sandbox.require = function (filename) {
// This modifies the global slightly, // This modifies the global slightly,
// but supplies vm with essential code // but supplies vm with essential code
return require(filename); return require(filename);
}; };
vm.runInNewContext(code, this.sandbox, fileName); vm.runInNewContext(code, sandbox, fileName);
}); });
after(function () { afterAll(function () {
//console.log(global); //console.log(global);
}); });
@ -45,7 +45,7 @@ describe("'global.root_path' set in js/app.js", function () {
expectedSubPaths.forEach((subpath) => { expectedSubPaths.forEach((subpath) => {
it(`contains a file/folder "${subpath}"`, function () { it(`contains a file/folder "${subpath}"`, function () {
expect(fs.existsSync(path.join(this.sandbox.global.root_path, subpath))).to.equal(true); expect(fs.existsSync(path.join(sandbox.global.root_path, subpath))).to.equal(true);
}); });
}); });
@ -59,6 +59,6 @@ describe("'global.root_path' set in js/app.js", function () {
it("should expect the global.version equals package.json file", function () { it("should expect the global.version equals package.json file", function () {
const versionPackage = JSON.parse(fs.readFileSync("package.json", "utf8")).version; const versionPackage = JSON.parse(fs.readFileSync("package.json", "utf8")).version;
expect(this.sandbox.global.version).to.equal(versionPackage); expect(sandbox.global.version).to.equal(versionPackage);
}); });
}); });