first commit
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
const path = require("path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
|
||||
describe("File js/class", () => {
|
||||
describe("Test function cloneObject", () => {
|
||||
let clone;
|
||||
let dom;
|
||||
|
||||
beforeAll((done) => {
|
||||
dom = new JSDOM(
|
||||
`<script>var Log = {log: () => {}};</script>\
|
||||
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "class.js")}">`,
|
||||
{ runScripts: "dangerously", resources: "usable" }
|
||||
);
|
||||
dom.window.onload = () => {
|
||||
const { cloneObject } = dom.window;
|
||||
clone = cloneObject;
|
||||
done();
|
||||
};
|
||||
});
|
||||
|
||||
it("should clone object", () => {
|
||||
const expected = { name: "Rodrigo", web: "https://rodrigoramirez.com", project: "MagicMirror" };
|
||||
const obj = clone(expected);
|
||||
expect(obj).toEqual(expected);
|
||||
expect(expected === obj).toBe(false);
|
||||
});
|
||||
|
||||
it("should clone array", () => {
|
||||
const expected = [1, null, undefined, "TEST"];
|
||||
const obj = clone(expected);
|
||||
expect(obj).toEqual(expected);
|
||||
expect(expected === obj).toBe(false);
|
||||
});
|
||||
|
||||
it("should clone number", () => {
|
||||
let expected = 1;
|
||||
let obj = clone(expected);
|
||||
expect(obj).toBe(expected);
|
||||
|
||||
expected = 1.23;
|
||||
obj = clone(expected);
|
||||
expect(obj).toBe(expected);
|
||||
});
|
||||
|
||||
it("should clone string", () => {
|
||||
const expected = "Perfect stranger";
|
||||
const obj = clone(expected);
|
||||
expect(obj).toBe(expected);
|
||||
});
|
||||
|
||||
it("should clone undefined", () => {
|
||||
const expected = undefined;
|
||||
const obj = clone(expected);
|
||||
expect(obj).toBe(expected);
|
||||
});
|
||||
|
||||
it("should clone null", () => {
|
||||
const expected = null;
|
||||
const obj = clone(expected);
|
||||
expect(obj).toBe(expected);
|
||||
});
|
||||
|
||||
it("should clone nested object", () => {
|
||||
const expected = {
|
||||
name: "fewieden",
|
||||
link: "https://github.com/fewieden",
|
||||
versions: ["2.0", "2.1", "2.2"],
|
||||
answerForAllQuestions: 42,
|
||||
properties: {
|
||||
items: [{ foo: "bar" }, { lorem: "ipsum" }],
|
||||
invalid: undefined,
|
||||
nothing: null
|
||||
}
|
||||
};
|
||||
const obj = clone(expected);
|
||||
expect(obj).toEqual(expected);
|
||||
expect(expected === obj).toBe(false);
|
||||
expect(expected.versions === obj.versions).toBe(false);
|
||||
expect(expected.properties === obj.properties).toBe(false);
|
||||
expect(expected.properties.items === obj.properties.items).toBe(false);
|
||||
expect(expected.properties.items[0] === obj.properties.items[0]).toBe(false);
|
||||
expect(expected.properties.items[1] === obj.properties.items[1]).toBe(false);
|
||||
});
|
||||
|
||||
describe("Test lockstring code", () => {
|
||||
let log;
|
||||
|
||||
beforeAll(() => {
|
||||
log = dom.window.Log.log;
|
||||
dom.window.Log.log = (str) => {
|
||||
expect(str).toBe("lockStrings");
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
dom.window.Log.log = log;
|
||||
});
|
||||
|
||||
it("should clone object and log lockStrings", () => {
|
||||
const expected = { name: "Module", lockStrings: "stringLock" };
|
||||
const obj = clone(expected);
|
||||
expect(obj).toEqual(expected);
|
||||
expect(expected === obj).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
const deprecated = require("../../../js/deprecated");
|
||||
|
||||
describe("Deprecated", () => {
|
||||
it("should be an object", () => {
|
||||
expect(typeof deprecated).toBe("object");
|
||||
});
|
||||
|
||||
it("should contain configs array with deprecated options as strings", () => {
|
||||
expect(Array.isArray(["deprecated.configs"])).toBe(true);
|
||||
for (let option of deprecated.configs) {
|
||||
expect(typeof option).toBe("string");
|
||||
}
|
||||
expect(deprecated.configs).toEqual(expect.arrayContaining(["kioskmode"]));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,285 @@
|
||||
const path = require("path");
|
||||
const helmet = require("helmet");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const express = require("express");
|
||||
|
||||
const sockets = new Set();
|
||||
|
||||
describe("Translator", () => {
|
||||
let server;
|
||||
|
||||
beforeAll(() => {
|
||||
const app = express();
|
||||
app.use(helmet());
|
||||
app.use((req, res, next) => {
|
||||
res.header("Access-Control-Allow-Origin", "*");
|
||||
next();
|
||||
});
|
||||
app.use("/translations", express.static(path.join(__dirname, "..", "..", "..", "tests", "mocks")));
|
||||
|
||||
server = app.listen(3000);
|
||||
|
||||
server.on("connection", (socket) => {
|
||||
sockets.add(socket);
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
sockets.delete(socket);
|
||||
}
|
||||
|
||||
await server.close();
|
||||
});
|
||||
|
||||
describe("translate", () => {
|
||||
const translations = {
|
||||
"MMM-Module": {
|
||||
Hello: "Hallo",
|
||||
"Hello {username}": "Hallo {username}"
|
||||
}
|
||||
};
|
||||
|
||||
const coreTranslations = {
|
||||
Hello: "XXX",
|
||||
"Hello {username}": "XXX",
|
||||
FOO: "Foo",
|
||||
"BAR {something}": "Bar {something}"
|
||||
};
|
||||
|
||||
const translationsFallback = {
|
||||
"MMM-Module": {
|
||||
Hello: "XXX",
|
||||
"Hello {username}": "XXX",
|
||||
FOO: "XXX",
|
||||
"BAR {something}": "XXX",
|
||||
"A key": "A translation"
|
||||
}
|
||||
};
|
||||
|
||||
const coreTranslationsFallback = {
|
||||
FOO: "XXX",
|
||||
"BAR {something}": "XXX",
|
||||
Hello: "XXX",
|
||||
"Hello {username}": "XXX",
|
||||
"A key": "XXX",
|
||||
Fallback: "core fallback"
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {object} Translator the global Translator object
|
||||
*/
|
||||
const setTranslations = (Translator) => {
|
||||
Translator.translations = translations;
|
||||
Translator.coreTranslations = coreTranslations;
|
||||
Translator.translationsFallback = translationsFallback;
|
||||
Translator.coreTranslationsFallback = coreTranslationsFallback;
|
||||
};
|
||||
|
||||
it("should return custom module translation", (done) => {
|
||||
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
|
||||
dom.window.onload = () => {
|
||||
const { Translator } = dom.window;
|
||||
setTranslations(Translator);
|
||||
let translation = Translator.translate({ name: "MMM-Module" }, "Hello");
|
||||
expect(translation).toBe("Hallo");
|
||||
translation = Translator.translate({ name: "MMM-Module" }, "Hello {username}", { username: "fewieden" });
|
||||
expect(translation).toBe("Hallo fewieden");
|
||||
done();
|
||||
};
|
||||
});
|
||||
|
||||
it("should return core translation", (done) => {
|
||||
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
|
||||
dom.window.onload = () => {
|
||||
const { Translator } = dom.window;
|
||||
setTranslations(Translator);
|
||||
let translation = Translator.translate({ name: "MMM-Module" }, "FOO");
|
||||
expect(translation).toBe("Foo");
|
||||
translation = Translator.translate({ name: "MMM-Module" }, "BAR {something}", { something: "Lorem Ipsum" });
|
||||
expect(translation).toBe("Bar Lorem Ipsum");
|
||||
done();
|
||||
};
|
||||
});
|
||||
|
||||
it("should return custom module translation fallback", (done) => {
|
||||
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
|
||||
dom.window.onload = () => {
|
||||
const { Translator } = dom.window;
|
||||
setTranslations(Translator);
|
||||
const translation = Translator.translate({ name: "MMM-Module" }, "A key");
|
||||
expect(translation).toBe("A translation");
|
||||
done();
|
||||
};
|
||||
});
|
||||
|
||||
it("should return core translation fallback", (done) => {
|
||||
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
|
||||
dom.window.onload = () => {
|
||||
const { Translator } = dom.window;
|
||||
setTranslations(Translator);
|
||||
const translation = Translator.translate({ name: "MMM-Module" }, "Fallback");
|
||||
expect(translation).toBe("core fallback");
|
||||
done();
|
||||
};
|
||||
});
|
||||
|
||||
it("should return translation with placeholder for missing variables", (done) => {
|
||||
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
|
||||
dom.window.onload = () => {
|
||||
const { Translator } = dom.window;
|
||||
setTranslations(Translator);
|
||||
const translation = Translator.translate({ name: "MMM-Module" }, "Hello {username}");
|
||||
expect(translation).toBe("Hallo {username}");
|
||||
done();
|
||||
};
|
||||
});
|
||||
|
||||
it("should return key if no translation was found", (done) => {
|
||||
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
|
||||
dom.window.onload = () => {
|
||||
const { Translator } = dom.window;
|
||||
setTranslations(Translator);
|
||||
const translation = Translator.translate({ name: "MMM-Module" }, "MISSING");
|
||||
expect(translation).toBe("MISSING");
|
||||
done();
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe("load", () => {
|
||||
const mmm = {
|
||||
name: "TranslationTest",
|
||||
file(file) {
|
||||
return `http://localhost:3000/translations/${file}`;
|
||||
}
|
||||
};
|
||||
|
||||
it("should load translations", (done) => {
|
||||
const dom = new JSDOM(`<script>var Log = {log: () => {}};</script><script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
|
||||
dom.window.onload = async () => {
|
||||
const { Translator } = dom.window;
|
||||
const file = "translation_test.json";
|
||||
|
||||
await Translator.load(mmm, file, false);
|
||||
const json = require(path.join(__dirname, "..", "..", "..", "tests", "mocks", file));
|
||||
expect(Translator.translations[mmm.name]).toEqual(json);
|
||||
done();
|
||||
};
|
||||
});
|
||||
|
||||
it("should load translation fallbacks", (done) => {
|
||||
const dom = new JSDOM(`<script>var Log = {log: () => {}};</script><script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
|
||||
dom.window.onload = async () => {
|
||||
const { Translator } = dom.window;
|
||||
const file = "translation_test.json";
|
||||
|
||||
await Translator.load(mmm, file, true);
|
||||
const json = require(path.join(__dirname, "..", "..", "..", "tests", "mocks", file));
|
||||
expect(Translator.translationsFallback[mmm.name]).toEqual(json);
|
||||
done();
|
||||
};
|
||||
});
|
||||
|
||||
it("should not load translations, if module fallback exists", (done) => {
|
||||
const dom = new JSDOM(`<script>var Log = {log: () => {}};</script><script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
|
||||
dom.window.onload = async () => {
|
||||
const { Translator, XMLHttpRequest } = dom.window;
|
||||
const file = "translation_test.json";
|
||||
|
||||
XMLHttpRequest.prototype.send = () => {
|
||||
throw new Error("Shouldn't load files");
|
||||
};
|
||||
|
||||
Translator.translationsFallback[mmm.name] = {
|
||||
Hello: "Hallo"
|
||||
};
|
||||
|
||||
await Translator.load(mmm, file, false);
|
||||
expect(Translator.translations[mmm.name]).toBe(undefined);
|
||||
expect(Translator.translationsFallback[mmm.name]).toEqual({
|
||||
Hello: "Hallo"
|
||||
});
|
||||
done();
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe("loadCoreTranslations", () => {
|
||||
it("should load core translations and fallback", (done) => {
|
||||
const dom = new JSDOM(
|
||||
`<script>var translations = {en: "http://localhost:3000/translations/translation_test.json"}; var Log = {log: () => {}};</script>\
|
||||
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`,
|
||||
{ runScripts: "dangerously", resources: "usable" }
|
||||
);
|
||||
dom.window.onload = async () => {
|
||||
const { Translator } = dom.window;
|
||||
await Translator.loadCoreTranslations("en");
|
||||
|
||||
const en = require(path.join(__dirname, "..", "..", "..", "tests", "mocks", "translation_test.json"));
|
||||
setTimeout(() => {
|
||||
expect(Translator.coreTranslations).toEqual(en);
|
||||
expect(Translator.coreTranslationsFallback).toEqual(en);
|
||||
done();
|
||||
}, 500);
|
||||
};
|
||||
});
|
||||
|
||||
it("should load core fallback if language cannot be found", (done) => {
|
||||
const dom = new JSDOM(
|
||||
`<script>var translations = {en: "http://localhost:3000/translations/translation_test.json"}; var Log = {log: () => {}};</script>\
|
||||
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`,
|
||||
{ runScripts: "dangerously", resources: "usable" }
|
||||
);
|
||||
dom.window.onload = async () => {
|
||||
const { Translator } = dom.window;
|
||||
await Translator.loadCoreTranslations("MISSINGLANG");
|
||||
|
||||
const en = require(path.join(__dirname, "..", "..", "..", "tests", "mocks", "translation_test.json"));
|
||||
setTimeout(() => {
|
||||
expect(Translator.coreTranslations).toEqual({});
|
||||
expect(Translator.coreTranslationsFallback).toEqual(en);
|
||||
done();
|
||||
}, 500);
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe("loadCoreTranslationsFallback", () => {
|
||||
it("should load core translations fallback", (done) => {
|
||||
const dom = new JSDOM(
|
||||
`<script>var translations = {en: "http://localhost:3000/translations/translation_test.json"}; var Log = {log: () => {}};</script>\
|
||||
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`,
|
||||
{ runScripts: "dangerously", resources: "usable" }
|
||||
);
|
||||
dom.window.onload = async () => {
|
||||
const { Translator } = dom.window;
|
||||
await Translator.loadCoreTranslationsFallback();
|
||||
|
||||
const en = require(path.join(__dirname, "..", "..", "..", "tests", "mocks", "translation_test.json"));
|
||||
setTimeout(() => {
|
||||
expect(Translator.coreTranslationsFallback).toEqual(en);
|
||||
done();
|
||||
}, 500);
|
||||
};
|
||||
});
|
||||
|
||||
it("should load core fallback if language cannot be found", (done) => {
|
||||
const dom = new JSDOM(
|
||||
`<script>var translations = {}; var Log = {log: () => {}};</script>\
|
||||
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`,
|
||||
{ runScripts: "dangerously", resources: "usable" }
|
||||
);
|
||||
dom.window.onload = async () => {
|
||||
const { Translator } = dom.window;
|
||||
await Translator.loadCoreTranslations();
|
||||
|
||||
setTimeout(() => {
|
||||
expect(Translator.coreTranslationsFallback).toEqual({});
|
||||
done();
|
||||
}, 500);
|
||||
};
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
const colors = require("colors/safe");
|
||||
const Utils = require("../../../js/utils");
|
||||
|
||||
describe("Utils", () => {
|
||||
describe("colors", () => {
|
||||
const colorsEnabled = colors.enabled;
|
||||
|
||||
afterEach(() => {
|
||||
colors.enabled = colorsEnabled;
|
||||
});
|
||||
|
||||
it("should have info, warn and error properties", () => {
|
||||
expect(Utils.colors).toHaveProperty("info");
|
||||
expect(Utils.colors).toHaveProperty("warn");
|
||||
expect(Utils.colors).toHaveProperty("error");
|
||||
});
|
||||
|
||||
it("properties should be functions", () => {
|
||||
expect(typeof Utils.colors.info).toBe("function");
|
||||
expect(typeof Utils.colors.warn).toBe("function");
|
||||
expect(typeof Utils.colors.error).toBe("function");
|
||||
});
|
||||
|
||||
it("should print colored message in supported consoles", () => {
|
||||
colors.enabled = true;
|
||||
expect(Utils.colors.info("some informations")).toBe("\u001b[34msome informations\u001b[39m");
|
||||
expect(Utils.colors.warn("a warning")).toBe("\u001b[33ma warning\u001b[39m");
|
||||
expect(Utils.colors.error("ERROR!")).toBe("\u001b[31mERROR!\u001b[39m");
|
||||
});
|
||||
|
||||
it("should print message in unsupported consoles", () => {
|
||||
colors.enabled = false;
|
||||
expect(Utils.colors.info("some informations")).toBe("some informations");
|
||||
expect(Utils.colors.warn("a warning")).toBe("a warning");
|
||||
expect(Utils.colors.error("ERROR!")).toBe("ERROR!");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`Updatenotification custom module returns status information without hash 1`] = `
|
||||
{
|
||||
"behind": 7,
|
||||
"current": "master",
|
||||
"hash": "",
|
||||
"isBehindInStatus": false,
|
||||
"module": "MMM-Fuel",
|
||||
"tracking": "origin/master",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Updatenotification MagicMirror on develop returns status information 1`] = `
|
||||
{
|
||||
"behind": 5,
|
||||
"current": "develop",
|
||||
"hash": "332e429a41f1a2339afd4f0ae96dd125da6beada",
|
||||
"isBehindInStatus": false,
|
||||
"module": "MagicMirror",
|
||||
"tracking": "origin/develop",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Updatenotification MagicMirror on develop returns status information early if isBehindInStatus 1`] = `
|
||||
{
|
||||
"behind": 5,
|
||||
"current": "develop",
|
||||
"hash": "332e429a41f1a2339afd4f0ae96dd125da6beada",
|
||||
"isBehindInStatus": true,
|
||||
"module": "MagicMirror",
|
||||
"tracking": "origin/develop",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Updatenotification MagicMirror on master (empty taglist) returns status information 1`] = `
|
||||
{
|
||||
"behind": 5,
|
||||
"current": "master",
|
||||
"hash": "332e429a41f1a2339afd4f0ae96dd125da6beada",
|
||||
"isBehindInStatus": false,
|
||||
"module": "MagicMirror",
|
||||
"tracking": "origin/master",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Updatenotification MagicMirror on master (empty taglist) returns status information early if isBehindInStatus 1`] = `
|
||||
{
|
||||
"behind": 5,
|
||||
"current": "master",
|
||||
"hash": "332e429a41f1a2339afd4f0ae96dd125da6beada",
|
||||
"isBehindInStatus": true,
|
||||
"module": "MagicMirror",
|
||||
"tracking": "origin/master",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Updatenotification MagicMirror on master with match in taglist returns status information 1`] = `
|
||||
{
|
||||
"behind": 5,
|
||||
"current": "master",
|
||||
"hash": "332e429a41f1a2339afd4f0ae96dd125da6beada",
|
||||
"isBehindInStatus": false,
|
||||
"module": "MagicMirror",
|
||||
"tracking": "origin/master",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Updatenotification MagicMirror on master with match in taglist returns status information early if isBehindInStatus 1`] = `
|
||||
{
|
||||
"behind": 5,
|
||||
"current": "master",
|
||||
"hash": "332e429a41f1a2339afd4f0ae96dd125da6beada",
|
||||
"isBehindInStatus": true,
|
||||
"module": "MagicMirror",
|
||||
"tracking": "origin/master",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Updatenotification MagicMirror on master without match in taglist returns status information 1`] = `
|
||||
{
|
||||
"behind": 0,
|
||||
"current": "master",
|
||||
"hash": "332e429a41f1a2339afd4f0ae96dd125da6beada",
|
||||
"isBehindInStatus": false,
|
||||
"module": "MagicMirror",
|
||||
"tracking": "origin/master",
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`Updatenotification MagicMirror on master without match in taglist returns status information early if isBehindInStatus 1`] = `
|
||||
{
|
||||
"behind": 0,
|
||||
"current": "master",
|
||||
"hash": "332e429a41f1a2339afd4f0ae96dd125da6beada",
|
||||
"isBehindInStatus": true,
|
||||
"module": "MagicMirror",
|
||||
"tracking": "origin/master",
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,31 @@
|
||||
const path = require("path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
|
||||
describe("Test function cmpVersions in js/module.js", () => {
|
||||
let cmp;
|
||||
|
||||
beforeAll((done) => {
|
||||
const dom = new JSDOM(
|
||||
`<script>var Class = {extend: () => { return {}; }};</script>\
|
||||
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "module.js")}">`,
|
||||
{ runScripts: "dangerously", resources: "usable" }
|
||||
);
|
||||
dom.window.onload = () => {
|
||||
const { cmpVersions } = dom.window;
|
||||
cmp = cmpVersions;
|
||||
done();
|
||||
};
|
||||
});
|
||||
|
||||
it("should return -1 when comparing 2.1 to 2.2", () => {
|
||||
expect(cmp("2.1", "2.2")).toBe(-1);
|
||||
});
|
||||
|
||||
it("should be return 0 when comparing 2.2 to 2.2", () => {
|
||||
expect(cmp("2.2", "2.2")).toBe(0);
|
||||
});
|
||||
|
||||
it("should be return 1 when comparing 1.1 to 1.0", () => {
|
||||
expect(cmp("1.1", "1.0")).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
const { cors } = require("../../../js/server_functions");
|
||||
|
||||
describe("server_functions tests", () => {
|
||||
describe("The cors method", () => {
|
||||
let fetchResponse;
|
||||
let fetchResponseHeadersGet;
|
||||
let fetchResponseHeadersText;
|
||||
let corsResponse;
|
||||
let request;
|
||||
|
||||
jest.mock("node-fetch");
|
||||
let nodefetch = require("node-fetch");
|
||||
let fetchMock;
|
||||
|
||||
beforeEach(() => {
|
||||
nodefetch.mockReset();
|
||||
|
||||
fetchResponseHeadersGet = jest.fn(() => {});
|
||||
fetchResponseHeadersText = jest.fn(() => {});
|
||||
fetchResponse = {
|
||||
headers: {
|
||||
get: fetchResponseHeadersGet
|
||||
},
|
||||
text: fetchResponseHeadersText
|
||||
};
|
||||
jest.mock("node-fetch", () => jest.fn());
|
||||
nodefetch.mockImplementation(() => fetchResponse);
|
||||
|
||||
fetchMock = nodefetch;
|
||||
|
||||
corsResponse = {
|
||||
set: jest.fn(() => {}),
|
||||
send: jest.fn(() => {})
|
||||
};
|
||||
|
||||
request = {
|
||||
url: `/cors?url=www.test.com`
|
||||
};
|
||||
});
|
||||
|
||||
test("Calls correct URL once", async () => {
|
||||
const urlToCall = "http://www.test.com/path?param1=value1";
|
||||
request.url = `/cors?url=${urlToCall}`;
|
||||
|
||||
await cors(request, corsResponse);
|
||||
|
||||
expect(fetchMock.mock.calls.length).toBe(1);
|
||||
expect(fetchMock.mock.calls[0][0]).toBe(urlToCall);
|
||||
});
|
||||
|
||||
test("Forewards Content-Type if json", async () => {
|
||||
fetchResponseHeadersGet.mockImplementation(() => "json");
|
||||
|
||||
await cors(request, corsResponse);
|
||||
|
||||
expect(fetchResponseHeadersGet.mock.calls.length).toBe(1);
|
||||
expect(fetchResponseHeadersGet.mock.calls[0][0]).toBe("Content-Type");
|
||||
|
||||
expect(corsResponse.set.mock.calls.length).toBe(1);
|
||||
expect(corsResponse.set.mock.calls[0][0]).toBe("Content-Type");
|
||||
expect(corsResponse.set.mock.calls[0][1]).toBe("json");
|
||||
});
|
||||
|
||||
test("Forewards Content-Type if xml", async () => {
|
||||
fetchResponseHeadersGet.mockImplementation(() => "xml");
|
||||
|
||||
await cors(request, corsResponse);
|
||||
|
||||
expect(fetchResponseHeadersGet.mock.calls.length).toBe(1);
|
||||
expect(fetchResponseHeadersGet.mock.calls[0][0]).toBe("Content-Type");
|
||||
|
||||
expect(corsResponse.set.mock.calls.length).toBe(1);
|
||||
expect(corsResponse.set.mock.calls[0][0]).toBe("Content-Type");
|
||||
expect(corsResponse.set.mock.calls[0][1]).toBe("xml");
|
||||
});
|
||||
|
||||
test("Sends correct data from response", async () => {
|
||||
const responseData = "some data";
|
||||
fetchResponseHeadersText.mockImplementation(() => responseData);
|
||||
|
||||
let sentData;
|
||||
corsResponse.send = jest.fn((input) => {
|
||||
sentData = input;
|
||||
});
|
||||
|
||||
await cors(request, corsResponse);
|
||||
|
||||
expect(fetchResponseHeadersText.mock.calls.length).toBe(1);
|
||||
expect(sentData).toBe(responseData);
|
||||
});
|
||||
|
||||
test("Sends error data from response", async () => {
|
||||
const error = new Error("error data");
|
||||
fetchResponseHeadersText.mockImplementation(() => {
|
||||
throw error;
|
||||
});
|
||||
|
||||
let sentData;
|
||||
corsResponse.send = jest.fn((input) => {
|
||||
sentData = input;
|
||||
});
|
||||
|
||||
await cors(request, corsResponse);
|
||||
|
||||
expect(fetchResponseHeadersText.mock.calls.length).toBe(1);
|
||||
expect(sentData).toBe(error);
|
||||
});
|
||||
|
||||
test("Fetches with user agent by default", async () => {
|
||||
await cors(request, corsResponse);
|
||||
|
||||
expect(fetchMock.mock.calls.length).toBe(1);
|
||||
expect(fetchMock.mock.calls[0][1]).toHaveProperty("headers");
|
||||
expect(fetchMock.mock.calls[0][1].headers).toHaveProperty("User-Agent");
|
||||
});
|
||||
|
||||
test("Fetches with specified headers", async () => {
|
||||
const headersParam = "sendheaders=header1:value1,header2:value2";
|
||||
const urlParam = "http://www.test.com/path?param1=value1";
|
||||
request.url = `/cors?${headersParam}&url=${urlParam}`;
|
||||
|
||||
await cors(request, corsResponse);
|
||||
|
||||
expect(fetchMock.mock.calls.length).toBe(1);
|
||||
expect(fetchMock.mock.calls[0][1]).toHaveProperty("headers");
|
||||
expect(fetchMock.mock.calls[0][1].headers).toHaveProperty("header1", "value1");
|
||||
expect(fetchMock.mock.calls[0][1].headers).toHaveProperty("header2", "value2");
|
||||
});
|
||||
|
||||
test("Sends specified headers", async () => {
|
||||
fetchResponseHeadersGet.mockImplementation((input) => input.replace("header", "value"));
|
||||
|
||||
const expectedheaders = "expectedheaders=header1,header2";
|
||||
const urlParam = "http://www.test.com/path?param1=value1";
|
||||
request.url = `/cors?${expectedheaders}&url=${urlParam}`;
|
||||
|
||||
await cors(request, corsResponse);
|
||||
|
||||
expect(fetchMock.mock.calls.length).toBe(1);
|
||||
expect(fetchMock.mock.calls[0][1]).toHaveProperty("headers");
|
||||
expect(corsResponse.set.mock.calls.length).toBe(3);
|
||||
expect(corsResponse.set.mock.calls[0][0]).toBe("Content-Type");
|
||||
expect(corsResponse.set.mock.calls[1][0]).toBe("header1");
|
||||
expect(corsResponse.set.mock.calls[1][1]).toBe("value1");
|
||||
expect(corsResponse.set.mock.calls[2][0]).toBe("header2");
|
||||
expect(corsResponse.set.mock.calls[2][1]).toBe("value2");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
jest.mock("util", () => ({
|
||||
...jest.requireActual("util"),
|
||||
promisify: jest.fn()
|
||||
}));
|
||||
|
||||
jest.mock("fs", () => ({
|
||||
...jest.requireActual("fs"),
|
||||
statSync: jest.fn()
|
||||
}));
|
||||
|
||||
jest.mock("logger", () => ({
|
||||
...jest.requireActual("logger"),
|
||||
error: jest.fn(),
|
||||
info: jest.fn()
|
||||
}));
|
||||
|
||||
describe("Updatenotification", () => {
|
||||
const execMock = jest.fn();
|
||||
|
||||
let gitHelper;
|
||||
|
||||
let gitRemoteOut;
|
||||
let gitRevParseOut;
|
||||
let gitStatusOut;
|
||||
let gitFetchOut;
|
||||
let gitRevListCountOut;
|
||||
let gitRevListOut;
|
||||
let gitFetchErr;
|
||||
let gitTagListOut;
|
||||
|
||||
beforeAll(async () => {
|
||||
const { promisify } = require("util");
|
||||
promisify.mockReturnValue(execMock);
|
||||
|
||||
const GitHelper = require(`../../../modules/default/updatenotification/git_helper`);
|
||||
gitHelper = new GitHelper();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
gitRemoteOut = "";
|
||||
gitRevParseOut = "";
|
||||
gitStatusOut = "";
|
||||
gitFetchOut = "";
|
||||
gitRevListCountOut = "";
|
||||
gitRevListOut = "";
|
||||
gitFetchErr = "";
|
||||
gitTagListOut = "";
|
||||
|
||||
execMock.mockImplementation((command) => {
|
||||
if (command.includes("git remote -v")) {
|
||||
return { stdout: gitRemoteOut };
|
||||
} else if (command.includes("git rev-parse HEAD")) {
|
||||
return { stdout: gitRevParseOut };
|
||||
} else if (command.includes("git status -sb")) {
|
||||
return { stdout: gitStatusOut };
|
||||
} else if (command.includes("git fetch -n --dry-run")) {
|
||||
return { stdout: gitFetchOut, stderr: gitFetchErr };
|
||||
} else if (command.includes("git rev-list --ancestry-path --count")) {
|
||||
return { stdout: gitRevListCountOut };
|
||||
} else if (command.includes("git rev-list --ancestry-path")) {
|
||||
return { stdout: gitRevListOut };
|
||||
} else if (command.includes("git ls-remote -q --tags --refs")) {
|
||||
return { stdout: gitTagListOut };
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
gitHelper.gitRepos = [];
|
||||
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("MagicMirror on develop", () => {
|
||||
const moduleName = "MagicMirror";
|
||||
|
||||
beforeEach(async () => {
|
||||
gitRemoteOut = "origin\tgit@github.com:MichMich/MagicMirror.git (fetch)\norigin\tgit@github.com:MichMich/MagicMirror.git (push)\n";
|
||||
gitRevParseOut = "332e429a41f1a2339afd4f0ae96dd125da6beada";
|
||||
gitStatusOut = "## develop...origin/develop\n M tests/unit/functions/updatenotification_spec.js\n";
|
||||
gitFetchErr = "From github.com:MichMich/MagicMirror\n60e0377..332e429 develop -> origin/develop\n";
|
||||
gitRevListCountOut = "5";
|
||||
|
||||
await gitHelper.add(moduleName);
|
||||
});
|
||||
|
||||
it("returns status information", async () => {
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos[0]).toMatchSnapshot();
|
||||
expect(execMock).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
|
||||
it("returns status information early if isBehindInStatus", async () => {
|
||||
gitStatusOut = "## develop...origin/develop [behind 5]";
|
||||
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos[0]).toMatchSnapshot();
|
||||
expect(execMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("excludes repo if status can't be retrieved", async () => {
|
||||
const errorMessage = "Failed to retrieve status";
|
||||
execMock.mockRejectedValueOnce(errorMessage);
|
||||
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos.length).toBe(0);
|
||||
|
||||
const { error } = require("logger");
|
||||
expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("MagicMirror on master (empty taglist)", () => {
|
||||
const moduleName = "MagicMirror";
|
||||
|
||||
beforeEach(async () => {
|
||||
gitRemoteOut = "origin\tgit@github.com:MichMich/MagicMirror.git (fetch)\norigin\tgit@github.com:MichMich/MagicMirror.git (push)\n";
|
||||
gitRevParseOut = "332e429a41f1a2339afd4f0ae96dd125da6beada";
|
||||
gitStatusOut = "## master...origin/master\n M tests/unit/functions/updatenotification_spec.js\n";
|
||||
gitFetchErr = "From github.com:MichMich/MagicMirror\n60e0377..332e429 master -> origin/master\n";
|
||||
gitRevListCountOut = "5";
|
||||
|
||||
await gitHelper.add(moduleName);
|
||||
});
|
||||
|
||||
it("returns status information", async () => {
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos[0]).toMatchSnapshot();
|
||||
expect(execMock).toHaveBeenCalledTimes(7);
|
||||
});
|
||||
|
||||
it("returns status information early if isBehindInStatus", async () => {
|
||||
gitStatusOut = "## master...origin/master [behind 5]";
|
||||
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos[0]).toMatchSnapshot();
|
||||
expect(execMock).toHaveBeenCalledTimes(7);
|
||||
});
|
||||
|
||||
it("excludes repo if status can't be retrieved", async () => {
|
||||
const errorMessage = "Failed to retrieve status";
|
||||
execMock.mockRejectedValueOnce(errorMessage);
|
||||
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos.length).toBe(0);
|
||||
|
||||
const { error } = require("logger");
|
||||
expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("MagicMirror on master with match in taglist", () => {
|
||||
const moduleName = "MagicMirror";
|
||||
|
||||
beforeEach(async () => {
|
||||
gitRemoteOut = "origin\tgit@github.com:MichMich/MagicMirror.git (fetch)\norigin\tgit@github.com:MichMich/MagicMirror.git (push)\n";
|
||||
gitRevParseOut = "332e429a41f1a2339afd4f0ae96dd125da6beada";
|
||||
gitStatusOut = "## master...origin/master\n M tests/unit/functions/updatenotification_spec.js\n";
|
||||
gitFetchErr = "From github.com:MichMich/MagicMirror\n60e0377..332e429 master -> origin/master\n";
|
||||
gitRevListCountOut = "5";
|
||||
gitTagListOut = "332e429a41f1a2339afd4f0ae96dd125da6beada...tag...\n";
|
||||
gitRevListOut = "332e429a41f1a2339afd4f0ae96dd125da6beada\n";
|
||||
|
||||
await gitHelper.add(moduleName);
|
||||
});
|
||||
|
||||
it("returns status information", async () => {
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos[0]).toMatchSnapshot();
|
||||
expect(execMock).toHaveBeenCalledTimes(7);
|
||||
});
|
||||
|
||||
it("returns status information early if isBehindInStatus", async () => {
|
||||
gitStatusOut = "## master...origin/master [behind 5]";
|
||||
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos[0]).toMatchSnapshot();
|
||||
expect(execMock).toHaveBeenCalledTimes(7);
|
||||
});
|
||||
|
||||
it("excludes repo if status can't be retrieved", async () => {
|
||||
const errorMessage = "Failed to retrieve status";
|
||||
execMock.mockRejectedValueOnce(errorMessage);
|
||||
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos.length).toBe(0);
|
||||
|
||||
const { error } = require("logger");
|
||||
expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("MagicMirror on master without match in taglist", () => {
|
||||
const moduleName = "MagicMirror";
|
||||
|
||||
beforeEach(async () => {
|
||||
gitRemoteOut = "origin\tgit@github.com:MichMich/MagicMirror.git (fetch)\norigin\tgit@github.com:MichMich/MagicMirror.git (push)\n";
|
||||
gitRevParseOut = "332e429a41f1a2339afd4f0ae96dd125da6beada";
|
||||
gitStatusOut = "## master...origin/master\n M tests/unit/functions/updatenotification_spec.js\n";
|
||||
gitFetchErr = "From github.com:MichMich/MagicMirror\n60e0377..332e429 master -> origin/master\n";
|
||||
gitRevListCountOut = "5";
|
||||
gitTagListOut = "xxxe429a41f1a2339afd4f0ae96dd125da6beada...tag...\n";
|
||||
gitRevListOut = "332e429a41f1a2339afd4f0ae96dd125da6beada\n";
|
||||
|
||||
await gitHelper.add(moduleName);
|
||||
});
|
||||
|
||||
it("returns status information", async () => {
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos[0]).toMatchSnapshot();
|
||||
expect(execMock).toHaveBeenCalledTimes(7);
|
||||
});
|
||||
|
||||
it("returns status information early if isBehindInStatus", async () => {
|
||||
gitStatusOut = "## master...origin/master [behind 5]";
|
||||
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos[0]).toMatchSnapshot();
|
||||
expect(execMock).toHaveBeenCalledTimes(7);
|
||||
});
|
||||
|
||||
it("excludes repo if status can't be retrieved", async () => {
|
||||
const errorMessage = "Failed to retrieve status";
|
||||
execMock.mockRejectedValueOnce(errorMessage);
|
||||
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos.length).toBe(0);
|
||||
|
||||
const { error } = require("logger");
|
||||
expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("custom module", () => {
|
||||
const moduleName = "MMM-Fuel";
|
||||
|
||||
beforeEach(async () => {
|
||||
gitRemoteOut = `origin\thttps://github.com/fewieden/${moduleName}.git (fetch)\norigin\thttps://github.com/fewieden/${moduleName}.git (push)\n`;
|
||||
gitRevParseOut = "9d8310163da94441073a93cead711ba43e8888d0";
|
||||
gitStatusOut = "## master...origin/master";
|
||||
gitFetchErr = `From https://github.com/fewieden/${moduleName}\n19f7faf..9d83101 master -> origin/master`;
|
||||
gitRevListCountOut = "7";
|
||||
|
||||
await gitHelper.add(moduleName);
|
||||
});
|
||||
|
||||
it("returns status information without hash", async () => {
|
||||
const repos = await gitHelper.getRepos();
|
||||
expect(repos[0]).toMatchSnapshot();
|
||||
expect(execMock).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const root_path = path.join(__dirname, "../../..");
|
||||
|
||||
describe("Default modules set in modules/default/defaultmodules.js", () => {
|
||||
const expectedDefaultModules = require("../../../modules/default/defaultmodules");
|
||||
|
||||
for (const defaultModule of expectedDefaultModules) {
|
||||
it(`contains a folder for modules/default/${defaultModule}"`, () => {
|
||||
expect(fs.existsSync(path.join(root_path, "modules/default", defaultModule))).toBe(true);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const root_path = path.join(__dirname, "../../..");
|
||||
const version = require(`${__dirname}/../../../package.json`).version;
|
||||
|
||||
describe("'global.root_path' set in js/app.js", () => {
|
||||
const expectedSubPaths = ["modules", "serveronly", "js", "js/app.js", "js/main.js", "js/electron.js", "config"];
|
||||
|
||||
expectedSubPaths.forEach((subpath) => {
|
||||
it(`contains a file/folder "${subpath}"`, () => {
|
||||
expect(fs.existsSync(path.join(root_path, subpath))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("should not modify global.root_path for testing", () => {
|
||||
expect(global.root_path).toBe(undefined);
|
||||
});
|
||||
|
||||
it("should not modify global.version for testing", () => {
|
||||
expect(global.version).toBe(undefined);
|
||||
});
|
||||
|
||||
it("should expect the global.version equals package.json file", () => {
|
||||
const versionPackage = JSON.parse(fs.readFileSync("package.json", "utf8")).version;
|
||||
expect(version).toBe(versionPackage);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
module.exports = async () => {
|
||||
process.env.TZ = "Europe/Berlin";
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
global.moment = require("moment-timezone");
|
||||
|
||||
const CalendarFetcherUtils = require("../../../../../modules/default/calendar/calendarfetcherutils");
|
||||
|
||||
describe("Calendar fetcher utils test", () => {
|
||||
const defaultConfig = {
|
||||
excludedEvents: [],
|
||||
includePastEvents: false,
|
||||
maximumEntries: 10,
|
||||
maximumNumberOfDays: 365
|
||||
};
|
||||
|
||||
describe("filterEvents", () => {
|
||||
it("should return only ongoing and upcoming non full day events", () => {
|
||||
const minusOneHour = moment().subtract(1, "hours").toDate();
|
||||
const minusTwoHours = moment().subtract(2, "hours").toDate();
|
||||
const plusOneHour = moment().add(1, "hours").toDate();
|
||||
const plusTwoHours = moment().add(2, "hours").toDate();
|
||||
|
||||
const filteredEvents = CalendarFetcherUtils.filterEvents(
|
||||
{
|
||||
pastEvent: { type: "VEVENT", start: minusTwoHours, end: minusOneHour, summary: "pastEvent" },
|
||||
ongoingEvent: { type: "VEVENT", start: minusOneHour, end: plusOneHour, summary: "ongoingEvent" },
|
||||
upcomingEvent: { type: "VEVENT", start: plusOneHour, end: plusTwoHours, summary: "upcomingEvent" }
|
||||
},
|
||||
defaultConfig
|
||||
);
|
||||
|
||||
expect(filteredEvents.length).toEqual(2);
|
||||
expect(filteredEvents[0].title).toBe("ongoingEvent");
|
||||
expect(filteredEvents[1].title).toBe("upcomingEvent");
|
||||
});
|
||||
|
||||
it("should return only ongoing and upcoming full day events", () => {
|
||||
const yesterday = moment().subtract(1, "days").startOf("day").toDate();
|
||||
const today = moment().startOf("day").toDate();
|
||||
const tomorrow = moment().add(1, "days").startOf("day").toDate();
|
||||
|
||||
const filteredEvents = CalendarFetcherUtils.filterEvents(
|
||||
{
|
||||
pastEvent: { type: "VEVENT", start: yesterday, end: yesterday, summary: "pastEvent" },
|
||||
ongoingEvent: { type: "VEVENT", start: today, end: today, summary: "ongoingEvent" },
|
||||
upcomingEvent: { type: "VEVENT", start: tomorrow, end: tomorrow, summary: "upcomingEvent" }
|
||||
},
|
||||
defaultConfig
|
||||
);
|
||||
|
||||
expect(filteredEvents.length).toEqual(2);
|
||||
expect(filteredEvents[0].title).toBe("ongoingEvent");
|
||||
expect(filteredEvents[1].title).toBe("upcomingEvent");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
global.moment = require("moment");
|
||||
|
||||
const CalendarUtils = require("../../../../../modules/default/calendar/calendarutils");
|
||||
|
||||
describe("Calendar utils tests", () => {
|
||||
describe("capFirst", () => {
|
||||
const words = {
|
||||
rodrigo: "Rodrigo",
|
||||
"123m": "123m",
|
||||
"magic mirror": "Magic mirror",
|
||||
",a": ",a",
|
||||
ñandú: "Ñandú"
|
||||
};
|
||||
|
||||
Object.keys(words).forEach((word) => {
|
||||
it(`for '${word}' should return '${words[word]}'`, () => {
|
||||
expect(CalendarUtils.capFirst(word)).toBe(words[word]);
|
||||
});
|
||||
});
|
||||
|
||||
it("should not capitalize other letters", () => {
|
||||
expect(CalendarUtils.capFirst("event")).not.toBe("EVent");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getLocaleSpecification", () => {
|
||||
it("should return a valid moment.LocaleSpecification for a 12-hour format", () => {
|
||||
expect(CalendarUtils.getLocaleSpecification(12)).toEqual({ longDateFormat: { LT: "h:mm A" } });
|
||||
});
|
||||
|
||||
it("should return a valid moment.LocaleSpecification for a 24-hour format", () => {
|
||||
expect(CalendarUtils.getLocaleSpecification(24)).toEqual({ longDateFormat: { LT: "HH:mm" } });
|
||||
});
|
||||
|
||||
it("should return the current system locale when called without timeFormat number", () => {
|
||||
expect(CalendarUtils.getLocaleSpecification()).toEqual({ longDateFormat: { LT: moment.localeData().longDateFormat("LT") } });
|
||||
});
|
||||
|
||||
it("should return a 12-hour longDateFormat when using the 'en' locale", () => {
|
||||
const localeBackup = moment.locale();
|
||||
moment.locale("en");
|
||||
expect(CalendarUtils.getLocaleSpecification()).toEqual({ longDateFormat: { LT: "h:mm A" } });
|
||||
moment.locale(localeBackup);
|
||||
});
|
||||
|
||||
it("should return a 12-hour longDateFormat when using the 'au' locale", () => {
|
||||
const localeBackup = moment.locale();
|
||||
moment.locale("au");
|
||||
expect(CalendarUtils.getLocaleSpecification()).toEqual({ longDateFormat: { LT: "h:mm A" } });
|
||||
moment.locale(localeBackup);
|
||||
});
|
||||
|
||||
it("should return a 12-hour longDateFormat when using the 'eg' locale", () => {
|
||||
const localeBackup = moment.locale();
|
||||
moment.locale("eg");
|
||||
expect(CalendarUtils.getLocaleSpecification()).toEqual({ longDateFormat: { LT: "h:mm A" } });
|
||||
moment.locale(localeBackup);
|
||||
});
|
||||
|
||||
it("should return a 24-hour longDateFormat when using the 'nl' locale", () => {
|
||||
const localeBackup = moment.locale();
|
||||
moment.locale("nl");
|
||||
expect(CalendarUtils.getLocaleSpecification()).toEqual({ longDateFormat: { LT: "HH:mm" } });
|
||||
moment.locale(localeBackup);
|
||||
});
|
||||
|
||||
it("should return a 24-hour longDateFormat when using the 'fr' locale", () => {
|
||||
const localeBackup = moment.locale();
|
||||
moment.locale("fr");
|
||||
expect(CalendarUtils.getLocaleSpecification()).toEqual({ longDateFormat: { LT: "HH:mm" } });
|
||||
moment.locale(localeBackup);
|
||||
});
|
||||
|
||||
it("should return a 24-hour longDateFormat when using the 'uk' locale", () => {
|
||||
const localeBackup = moment.locale();
|
||||
moment.locale("uk");
|
||||
expect(CalendarUtils.getLocaleSpecification()).toEqual({ longDateFormat: { LT: "HH:mm" } });
|
||||
moment.locale(localeBackup);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shorten", () => {
|
||||
it("should not shorten if short enough", () => {
|
||||
expect(CalendarUtils.shorten("Event 1", 10, false, 1)).toBe("Event 1");
|
||||
});
|
||||
|
||||
it("should shorten into one line", () => {
|
||||
expect(CalendarUtils.shorten("Example event at 12 o clock", 10, true, 1)).toBe("Example …");
|
||||
});
|
||||
|
||||
it("should shorten into three lines", () => {
|
||||
expect(CalendarUtils.shorten("Example event at 12 o clock", 10, true, 3)).toBe("Example <br>event at 12 o <br>clock");
|
||||
});
|
||||
|
||||
it("should not shorten into three lines if wrap is false", () => {
|
||||
expect(CalendarUtils.shorten("Example event at 12 o clock", 10, false, 3)).toBe("Example ev…");
|
||||
});
|
||||
|
||||
const strings = {
|
||||
" String with whitespace at the beginning that needs trimming": { length: 16, return: "String with whit…" },
|
||||
"long string that needs shortening": { length: 16, return: "long string that…" },
|
||||
"short string": { length: 16, return: "short string" },
|
||||
"long string with no maxLength defined": { return: "long string with no maxLength defined" }
|
||||
};
|
||||
|
||||
Object.keys(strings).forEach((string) => {
|
||||
it(`for '${string}' should return '${strings[string].return}'`, () => {
|
||||
expect(CalendarUtils.shorten(string, strings[string].length)).toBe(strings[string].return);
|
||||
});
|
||||
});
|
||||
|
||||
it("should return an empty string if shorten is called with a non-string", () => {
|
||||
expect(CalendarUtils.shorten(100)).toBe("");
|
||||
});
|
||||
|
||||
it("should not shorten the string if shorten is called with a non-number maxLength", () => {
|
||||
expect(CalendarUtils.shorten("This is a test string", "This is not a number")).toBe("This is a test string");
|
||||
});
|
||||
|
||||
it("should wrap the string instead of shorten it if shorten is called with wrapEvents = true (with maxLength defined as 20)", () => {
|
||||
expect(CalendarUtils.shorten("This is a wrapEvent test. Should wrap the string instead of shorten it if called with wrapEvent = true", 20, true)).toBe(
|
||||
"This is a <br>wrapEvent test. Should wrap <br>the string instead of <br>shorten it if called with <br>wrapEvent = true"
|
||||
);
|
||||
});
|
||||
|
||||
it("should wrap the string instead of shorten it if shorten is called with wrapEvents = true (without maxLength defined, default 25)", () => {
|
||||
expect(CalendarUtils.shorten("This is a wrapEvent test. Should wrap the string instead of shorten it if called with wrapEvent = true", undefined, true)).toBe(
|
||||
"This is a wrapEvent <br>test. Should wrap the string <br>instead of shorten it if called <br>with wrapEvent = true"
|
||||
);
|
||||
});
|
||||
|
||||
it("should wrap and shorten the string in the second line if called with wrapEvents = true and maxTitleLines = 2", () => {
|
||||
expect(CalendarUtils.shorten("This is a wrapEvent and maxTitleLines test. Should wrap and shorten the string in the second line if called with wrapEvents = true and maxTitleLines = 2", undefined, true, 2)).toBe(
|
||||
"This is a wrapEvent and <br>maxTitleLines test. Should wrap and …"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("titleTransform and shorten combined", () => {
|
||||
it("should replace the birthday and wrap nicely", () => {
|
||||
const transformedTitle = CalendarUtils.titleTransform("Michael Teeuw's birthday", {
|
||||
"De verjaardag van ": "",
|
||||
"'s birthday": ""
|
||||
});
|
||||
expect(CalendarUtils.shorten(transformedTitle, 10, true, 2)).toBe("Michael <br>Teeuw");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
global.moment = require("moment-timezone");
|
||||
const { performWebRequest, formatTime } = require("../../../../modules/default/utils");
|
||||
|
||||
const nodeVersion = process.version.match(/^v(\d+)\.*/)[1];
|
||||
|
||||
describe("Default modules utils tests", () => {
|
||||
describe("performWebRequest", () => {
|
||||
if (nodeVersion > 18) {
|
||||
const locationHost = "localhost:8080";
|
||||
const locationProtocol = "http";
|
||||
|
||||
let fetchResponse;
|
||||
let fetchMock;
|
||||
let urlToCall;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchResponse = new Response();
|
||||
global.fetch = jest.fn(() => Promise.resolve(fetchResponse));
|
||||
fetchMock = global.fetch;
|
||||
});
|
||||
|
||||
describe("When using cors proxy", () => {
|
||||
Object.defineProperty(global, "location", {
|
||||
value: {
|
||||
host: locationHost,
|
||||
protocol: locationProtocol
|
||||
}
|
||||
});
|
||||
|
||||
test("Calls correct URL once", async () => {
|
||||
urlToCall = "http://www.test.com/path?param1=value1";
|
||||
|
||||
await performWebRequest(urlToCall, "json", true);
|
||||
|
||||
expect(fetchMock.mock.calls.length).toBe(1);
|
||||
expect(fetchMock.mock.calls[0][0]).toBe(`${locationProtocol}//${locationHost}/cors?url=${urlToCall}`);
|
||||
});
|
||||
|
||||
test("Sends correct headers", async () => {
|
||||
urlToCall = "http://www.test.com/path?param1=value1";
|
||||
|
||||
const headers = [
|
||||
{ name: "header1", value: "value1" },
|
||||
{ name: "header2", value: "value2" }
|
||||
];
|
||||
|
||||
await performWebRequest(urlToCall, "json", true, headers);
|
||||
|
||||
expect(fetchMock.mock.calls.length).toBe(1);
|
||||
expect(fetchMock.mock.calls[0][0]).toBe(`${locationProtocol}//${locationHost}/cors?sendheaders=header1:value1,header2:value2&url=${urlToCall}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("When not using cors proxy", () => {
|
||||
test("Calls correct URL once", async () => {
|
||||
urlToCall = "http://www.test.com/path?param1=value1";
|
||||
|
||||
await performWebRequest(urlToCall);
|
||||
|
||||
expect(fetchMock.mock.calls.length).toBe(1);
|
||||
expect(fetchMock.mock.calls[0][0]).toBe(urlToCall);
|
||||
});
|
||||
|
||||
test("Sends correct headers", async () => {
|
||||
urlToCall = "http://www.test.com/path?param1=value1";
|
||||
const headers = [
|
||||
{ name: "header1", value: "value1" },
|
||||
{ name: "header2", value: "value2" }
|
||||
];
|
||||
|
||||
await performWebRequest(urlToCall, "json", false, headers);
|
||||
|
||||
const expectedHeaders = { headers: { header1: "value1", header2: "value2" } };
|
||||
expect(fetchMock.mock.calls.length).toBe(1);
|
||||
expect(fetchMock.mock.calls[0][1]).toStrictEqual(expectedHeaders);
|
||||
});
|
||||
});
|
||||
|
||||
describe("When receiving json format", () => {
|
||||
test("Returns undefined when no data is received", async () => {
|
||||
urlToCall = "www.test.com";
|
||||
|
||||
const response = await performWebRequest(urlToCall);
|
||||
|
||||
expect(response).toBe(undefined);
|
||||
});
|
||||
|
||||
test("Returns object when data is received", async () => {
|
||||
urlToCall = "www.test.com";
|
||||
fetchResponse = new Response('{"body": "some content"}');
|
||||
|
||||
const response = await performWebRequest(urlToCall);
|
||||
|
||||
expect(response.body).toBe("some content");
|
||||
});
|
||||
|
||||
test("Returns expected headers when data is received", async () => {
|
||||
urlToCall = "www.test.com";
|
||||
fetchResponse = new Response('{"body": "some content"}', { headers: { header1: "value1", header2: "value2" } });
|
||||
|
||||
const response = await performWebRequest(urlToCall, "json", false, undefined, ["header1"]);
|
||||
|
||||
expect(response.headers.length).toBe(1);
|
||||
expect(response.headers[0].name).toBe("header1");
|
||||
expect(response.headers[0].value).toBe("value1");
|
||||
});
|
||||
});
|
||||
} else {
|
||||
test("Always ok, need one test", () => {});
|
||||
}
|
||||
});
|
||||
|
||||
describe("formatTime", () => {
|
||||
const time = new Date();
|
||||
|
||||
beforeEach(async () => {
|
||||
time.setHours(13, 13);
|
||||
});
|
||||
|
||||
it("should convert correctly according to the config", () => {
|
||||
expect(
|
||||
formatTime(
|
||||
{
|
||||
timeFormat: 24
|
||||
},
|
||||
time
|
||||
)
|
||||
).toBe("13:13");
|
||||
expect(
|
||||
formatTime(
|
||||
{
|
||||
showPeriod: true,
|
||||
showPeriodUpper: true,
|
||||
timeFormat: 12
|
||||
},
|
||||
time
|
||||
)
|
||||
).toBe("1:13 PM");
|
||||
expect(
|
||||
formatTime(
|
||||
{
|
||||
showPeriod: true,
|
||||
showPeriodUpper: false,
|
||||
timeFormat: 12
|
||||
},
|
||||
time
|
||||
)
|
||||
).toBe("1:13 pm");
|
||||
expect(
|
||||
formatTime(
|
||||
{
|
||||
showPeriod: false,
|
||||
timeFormat: 12
|
||||
},
|
||||
time
|
||||
)
|
||||
).toBe("1:13");
|
||||
});
|
||||
|
||||
it("should convert correctly into another timezone", () => {
|
||||
expect(
|
||||
formatTime(
|
||||
{
|
||||
timeFormat: 24,
|
||||
timezone: "America/Toronto"
|
||||
},
|
||||
time
|
||||
)
|
||||
).toBe("07:13");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
const WeatherObject = require("../../../../../modules/default/weather/weatherobject");
|
||||
|
||||
global.moment = require("moment-timezone");
|
||||
global.SunCalc = require("suncalc");
|
||||
|
||||
describe("WeatherObject", () => {
|
||||
let originalTimeZone;
|
||||
let weatherobject;
|
||||
|
||||
beforeAll(() => {
|
||||
originalTimeZone = moment.tz.guess();
|
||||
moment.tz.setDefault("Africa/Dar_es_Salaam");
|
||||
weatherobject = new WeatherObject();
|
||||
});
|
||||
|
||||
it("should return true for daytime at noon", () => {
|
||||
weatherobject.date = moment("12:00", "HH:mm");
|
||||
weatherobject.updateSunTime(-6.774877582342688, 37.63345667023327);
|
||||
expect(weatherobject.isDayTime()).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for daytime at midnight", () => {
|
||||
weatherobject.date = moment("00:00", "HH:mm");
|
||||
weatherobject.updateSunTime(-6.774877582342688, 37.63345667023327);
|
||||
expect(weatherobject.isDayTime()).toBe(false);
|
||||
});
|
||||
|
||||
it("should return sunrise as the next sunaction", () => {
|
||||
weatherobject.updateSunTime(-6.774877582342688, 37.63345667023327);
|
||||
let midnight = moment("00:00", "HH:mm");
|
||||
expect(weatherobject.nextSunAction(midnight)).toBe("sunrise");
|
||||
});
|
||||
|
||||
it("should return sunset as the next sunaction", () => {
|
||||
weatherobject.updateSunTime(-6.774877582342688, 37.63345667023327);
|
||||
let noon = moment(weatherobject.sunrise).hour(14);
|
||||
expect(weatherobject.nextSunAction(noon)).toBe("sunset");
|
||||
});
|
||||
|
||||
it("should return an already defined feelsLike info", () => {
|
||||
weatherobject.feelsLikeTemp = "feelsLikeTempValue";
|
||||
expect(weatherobject.feelsLike()).toBe("feelsLikeTempValue");
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
moment.tz.setDefault(originalTimeZone);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
const weather = require("../../../../../modules/default/weather/weatherutils");
|
||||
const WeatherUtils = require("../../../../../modules/default/weather/weatherutils");
|
||||
|
||||
describe("Weather utils tests", () => {
|
||||
describe("windspeed conversion", () => {
|
||||
it("should convert windspeed correctly from mps to beaufort", () => {
|
||||
expect(Math.round(WeatherUtils.convertWind(5, "beaufort"))).toBe(3);
|
||||
expect(Math.round(WeatherUtils.convertWind(300, "beaufort"))).toBe(12);
|
||||
});
|
||||
|
||||
it("should convert windspeed correctly from mps to mps", () => {
|
||||
expect(WeatherUtils.convertWind(11.75, "FOOBAR")).toBe(11.75);
|
||||
});
|
||||
|
||||
it("should convert windspeed correctly from mps to kmh", () => {
|
||||
expect(Math.round(WeatherUtils.convertWind(11.75, "kmh"))).toBe(42);
|
||||
});
|
||||
|
||||
it("should convert windspeed correctly from mps to knots", () => {
|
||||
expect(Math.round(WeatherUtils.convertWind(10, "knots"))).toBe(19);
|
||||
});
|
||||
|
||||
it("should convert windspeed correctly from mph to mps", () => {
|
||||
expect(Math.round(WeatherUtils.convertWindToMetric(93.951324266285))).toBe(42);
|
||||
});
|
||||
|
||||
it("should convert windspeed correctly from kmh to mps", () => {
|
||||
expect(Math.round(WeatherUtils.convertWindToMs(151.2))).toBe(42);
|
||||
});
|
||||
});
|
||||
|
||||
describe("wind direction conversion", () => {
|
||||
it("should convert wind direction correctly from cardinal to value", () => {
|
||||
expect(WeatherUtils.convertWindDirection("SSE")).toBe(157);
|
||||
});
|
||||
});
|
||||
|
||||
describe("feelsLike calculation", () => {
|
||||
it("should return a calculated feelsLike info", () => {
|
||||
expect(WeatherUtils.calculateFeelsLike(0, 20, 40)).toBe(-9.444444444444445);
|
||||
});
|
||||
|
||||
it("should return a calculated feelsLike info", () => {
|
||||
expect(WeatherUtils.calculateFeelsLike(30, 0, 60)).toBe(32.8320322777777);
|
||||
});
|
||||
});
|
||||
|
||||
describe("precipitationUnit conversion", () => {
|
||||
it("should keep value and unit if outputUnit is undefined", () => {
|
||||
const values = [1, 2];
|
||||
const units = ["mm", "cm"];
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
const result = weather.convertPrecipitationUnit(values[i], units[i], undefined);
|
||||
expect(result).toBe(`${values[i].toFixed(2)} ${units[i]}`);
|
||||
}
|
||||
});
|
||||
|
||||
it("should keep value and unit if outputUnit is metric", () => {
|
||||
const values = [1, 2];
|
||||
const units = ["mm", "cm"];
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
const result = weather.convertPrecipitationUnit(values[i], units[i], "metric");
|
||||
expect(result).toBe(`${values[i].toFixed(2)} ${units[i]}`);
|
||||
}
|
||||
});
|
||||
|
||||
it("should use mm unit if input unit is undefined", () => {
|
||||
const values = [1, 2];
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
const result = weather.convertPrecipitationUnit(values[i], undefined, "metric");
|
||||
expect(result).toBe(`${values[i].toFixed(2)} mm`);
|
||||
}
|
||||
});
|
||||
|
||||
it("should convert value and unit if outputUnit is imperial", () => {
|
||||
const values = [1, 2];
|
||||
const units = ["mm", "cm"];
|
||||
const expectedValues = [0.04, 0.79];
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
const result = weather.convertPrecipitationUnit(values[i], units[i], "imperial");
|
||||
expect(result).toBe(`${expectedValues[i]} in`);
|
||||
}
|
||||
});
|
||||
|
||||
it("should round percentage values regardless of output units", () => {
|
||||
const values = [0.1, 2.22, 9.999];
|
||||
const output = [undefined, "imperial", "metric"];
|
||||
const result = ["0 %", "2 %", "10 %"];
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
expect(weather.convertPrecipitationUnit(values[i], "%", output[i])).toBe(result[i]);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user