Release 2.33.0 (#3903)

This commit is contained in:
Kristjan ESPERANTO
2025-09-30 18:02:22 +02:00
committed by GitHub
parent 62b0f7f26e
commit b0c5924019
77 changed files with 2811 additions and 2654 deletions

View File

@@ -0,0 +1,18 @@
let config = {
address: "0.0.0.0",
ipWhitelist: [],
modules: [
{
module: "alert",
config: {
display_time: 1000000,
welcome_message: false
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = config;
}

View File

@@ -0,0 +1,18 @@
let config = {
address: "0.0.0.0",
ipWhitelist: [],
modules: [
{
module: "alert",
config: {
display_time: 1000000,
welcome_message: "Custom welcome message!"
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = config;
}

View File

@@ -1,43 +1,79 @@
const helpers = require("./helpers/global-setup");
// Validate Animate.css integration for compliments module using class toggling.
// We intentionally ignore computed animation styles (jsdom doesn't simulate real animations).
describe("AnimateCSS integration Test", () => {
// define config file for testing
let testConfigFile = "tests/configs/modules/compliments/compliments_animateCSS.js";
// define config file to fallback to default: wrong animation name (must return no animation)
let testConfigFileFallbackToDefault = "tests/configs/modules/compliments/compliments_animateCSS_fallbackToDefault.js";
// define config file with an inverted name animation : in for out and vice versa (must return no animation)
let testConfigFileInvertedAnimationName = "tests/configs/modules/compliments/compliments_animateCSS_invertedAnimationName.js";
// define config file with no animation defined
let testConfigByDefault = "tests/configs/modules/compliments/compliments_anytime.js";
// Config variants under test
const TEST_CONFIG_ANIM = "tests/configs/modules/compliments/compliments_animateCSS.js";
const TEST_CONFIG_FALLBACK = "tests/configs/modules/compliments/compliments_animateCSS_fallbackToDefault.js"; // invalid animation names
const TEST_CONFIG_INVERTED = "tests/configs/modules/compliments/compliments_animateCSS_invertedAnimationName.js"; // in/out swapped
const TEST_CONFIG_NONE = "tests/configs/modules/compliments/compliments_anytime.js"; // no animations defined
/**
* move similar tests in function doTest
* @param {string} [animationIn] animation in name of AnimateCSS to test.
* @param {string} [animationOut] animation out name of AnimateCSS to test.
* @returns {boolean} result
* Get the compliments container element (waits until available).
* @returns {Promise<HTMLElement>} compliments root element
*/
const doTest = async (animationIn, animationOut) => {
async function getComplimentsElement () {
await helpers.getDocument();
let elem = await helpers.waitForElement(".compliments");
expect(elem).not.toBeNull();
let styles = window.getComputedStyle(elem);
const el = await helpers.waitForElement(".compliments");
expect(el).not.toBeNull();
return el;
}
if (animationIn && animationIn !== "") {
expect(styles._values.get("animation-name")).toBe(animationIn);
} else {
expect(styles._values.get("animation-name")).toBeUndefined();
/**
* Wait for an Animate.css class to appear and persist briefly.
* @param {string} cls Animation class name without leading dot (e.g. animate__flipInX)
* @param {{timeout?: number}} [options] Poll timeout in ms (default 6000)
* @returns {Promise<boolean>} true if class detected in time
*/
async function waitForAnimationClass (cls, { timeout = 6000 } = {}) {
const start = Date.now();
while (Date.now() - start < timeout) {
if (document.querySelector(`.compliments.animate__animated.${cls}`)) {
// small stability wait
await new Promise((r) => setTimeout(r, 50));
if (document.querySelector(`.compliments.animate__animated.${cls}`)) return true;
}
await new Promise((r) => setTimeout(r, 100));
}
throw new Error(`Timeout waiting for class ${cls}`);
}
if (animationOut && animationOut !== "") {
elem = await helpers.waitForElement(`.compliments.animate__animated.animate__${animationOut}`);
expect(elem).not.toBeNull();
styles = window.getComputedStyle(elem);
expect(styles._values.get("animation-name")).toBe(animationOut);
} else {
expect(styles._values.get("animation-name")).toBeUndefined();
/**
* Assert that no Animate.css animation class is applied within a time window.
* @param {number} [ms] Observation period in ms (default 2000)
* @returns {Promise<void>}
*/
async function assertNoAnimationWithin (ms = 2000) {
const start = Date.now();
while (Date.now() - start < ms) {
if (document.querySelector(".compliments.animate__animated")) {
throw new Error("Unexpected animate__animated class present in non-animation scenario");
}
await new Promise((r) => setTimeout(r, 100));
}
}
/**
* Run one animation test scenario.
* @param {string} [animationIn] Expected animate-in name
* @param {string} [animationOut] Expected animate-out name
* @returns {Promise<boolean>} true when scenario assertions pass
*/
async function runAnimationTest (animationIn, animationOut) {
await getComplimentsElement();
if (!animationIn && !animationOut) {
await assertNoAnimationWithin(2000);
return true;
}
if (animationIn) await waitForAnimationClass(`animate__${animationIn}`);
if (animationOut) {
// Wait just beyond one update cycle (updateInterval=2000ms) before expecting animateOut.
await new Promise((r) => setTimeout(r, 2100));
await waitForAnimationClass(`animate__${animationOut}`);
}
return true;
};
}
afterEach(async () => {
await helpers.stopApplication();
@@ -45,29 +81,29 @@ describe("AnimateCSS integration Test", () => {
describe("animateIn and animateOut Test", () => {
it("with flipInX and flipOutX animation", async () => {
await helpers.startApplication(testConfigFile);
await expect(doTest("flipInX", "flipOutX")).resolves.toBe(true);
await helpers.startApplication(TEST_CONFIG_ANIM);
await expect(runAnimationTest("flipInX", "flipOutX")).resolves.toBe(true);
});
});
describe("use animateOut name for animateIn (vice versa) Test", () => {
it("without animation", async () => {
await helpers.startApplication(testConfigFileInvertedAnimationName);
await expect(doTest()).resolves.toBe(true);
it("without animation (inverted names)", async () => {
await helpers.startApplication(TEST_CONFIG_INVERTED);
await expect(runAnimationTest()).resolves.toBe(true);
});
});
describe("false Animation name test", () => {
it("without animation", async () => {
await helpers.startApplication(testConfigFileFallbackToDefault);
await expect(doTest()).resolves.toBe(true);
it("without animation (invalid names)", async () => {
await helpers.startApplication(TEST_CONFIG_FALLBACK);
await expect(runAnimationTest()).resolves.toBe(true);
});
});
describe("no Animation defined test", () => {
it("without animation", async () => {
await helpers.startApplication(testConfigByDefault);
await expect(doTest()).resolves.toBe(true);
it("without animation (no config)", async () => {
await helpers.startApplication(TEST_CONFIG_NONE);
await expect(runAnimationTest()).resolves.toBe(true);
});
});
});

View File

@@ -3,7 +3,7 @@ const helpers = require("./helpers/global-setup");
describe("All font files from roboto.css should be downloadable", () => {
const fontFiles = [];
// Statements below filters out all 'url' lines in the CSS file
const fileContent = require("node:fs").readFileSync(`${__dirname}/../../css/roboto.css`, "utf8");
const fileContent = require("node:fs").readFileSync(`${global.root_path}/css/roboto.css`, "utf8");
const regex = /\burl\(['"]([^'"]+)['"]\)/g;
let match = regex.exec(fileContent);
while (match !== null) {

View File

@@ -13,10 +13,9 @@ app.use(basicAuth);
// Set available directories
const directories = ["/tests/configs", "/tests/mocks"];
const rootPath = path.resolve(`${__dirname}/../../../`);
for (let directory of directories) {
app.use(directory, express.static(path.resolve(rootPath + directory)));
app.use(directory, express.static(path.resolve(`${global.root_path}/${directory}`)));
}
let server;

View File

@@ -1,9 +1,13 @@
const path = require("node:path");
const os = require("node:os");
const fs = require("node:fs");
const jsdom = require("jsdom");
const indexFile = `${__dirname}/../../../index.html`;
const cssFile = `${__dirname}/../../../css/custom.css`;
// global absolute root path
global.root_path = path.resolve(`${__dirname}/../../../`);
const indexFile = `${global.root_path}/index.html`;
const cssFile = `${global.root_path}/css/custom.css`;
const sampleCss = [
".region.row3 {",
" top: 0;",
@@ -29,12 +33,12 @@ exports.startApplication = async (configFilename, exec) => {
process.env.mmTestMode = "true";
process.setMaxListeners(0);
if (exec) exec;
global.app = require("../../../js/app");
global.app = require(`${global.root_path}/js/app`);
return global.app.start();
};
exports.stopApplication = async (waitTime = 1000) => {
exports.stopApplication = async (waitTime = 10) => {
if (global.window) {
// no closing causes jest errors and memory leaks
global.window.close();

View File

@@ -1,4 +1,4 @@
const { injectMockData } = require("../../utils/weather_mocker");
const { injectMockData, cleanupMockData } = require("../../utils/weather_mocker");
const helpers = require("./global-setup");
exports.getText = async (element, result) => {
@@ -13,7 +13,12 @@ exports.getText = async (element, result) => {
return true;
};
exports.startApp = async (configFileName, additionalMockData) => {
exports.startApplication = async (configFileName, additionalMockData) => {
await helpers.startApplication(injectMockData(configFileName, additionalMockData));
await helpers.getDocument();
};
exports.stopApplication = async () => {
await helpers.stopApplication();
cleanupMockData();
};

View File

@@ -1,17 +1,52 @@
const helpers = require("../helpers/global-setup");
describe("Alert module", () => {
beforeAll(async () => {
await helpers.startApplication("tests/configs/modules/alert/default.js");
await helpers.getDocument();
});
afterAll(async () => {
await helpers.stopApplication();
});
it("should show the welcome message", async () => {
const elem = await helpers.waitForElement(".ns-box .ns-box-inner .light.bright.small");
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("Welcome, start was successful!");
describe("with welcome_message set to false", () => {
beforeAll(async () => {
await helpers.startApplication("tests/configs/modules/alert/welcome_false.js");
await helpers.getDocument();
});
it("should not show any welcome message", async () => {
// Wait a bit to ensure no message appears
await new Promise((resolve) => setTimeout(resolve, 1000));
// Check that no alert/notification elements are present
const alertElements = document.querySelectorAll(".ns-box .ns-box-inner .light.bright.small");
expect(alertElements).toHaveLength(0);
});
});
describe("with welcome_message set to true", () => {
beforeAll(async () => {
await helpers.startApplication("tests/configs/modules/alert/welcome_true.js");
await helpers.getDocument();
// Wait for the application to initialize
await new Promise((resolve) => setTimeout(resolve, 1000));
});
it("should show the translated welcome message", async () => {
const elem = await helpers.waitForElement(".ns-box .ns-box-inner .light.bright.small");
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("Welcome, start was successful!");
});
});
describe("with welcome_message set to custom string", () => {
beforeAll(async () => {
await helpers.startApplication("tests/configs/modules/alert/welcome_string.js");
await helpers.getDocument();
});
it("should show the custom welcome message", async () => {
const elem = await helpers.waitForElement(".ns-box .ns-box-inner .light.bright.small");
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("Custom welcome message!");
});
});
});

View File

@@ -42,7 +42,7 @@ describe("Calendar module", () => {
});
it("should show the default calendar symbol in each event", async () => {
await expect(testElementLength(".calendar .event .fa-calendar-alt", 0, "not")).resolves.toBe(true);
await expect(testElementLength(".calendar .event .fa-calendar-days", 0, "not")).resolves.toBe(true);
});
});

View File

@@ -83,8 +83,7 @@ describe("Newsfeed module", () => {
describe("Newsfeed module located in config directory", () => {
beforeAll(() => {
const baseDir = `${__dirname}/../../..`;
fs.cpSync(`${baseDir}/modules/default/newsfeed`, `${baseDir}/config/newsfeed`, { recursive: true });
fs.cpSync(`${global.root_path}/modules/default/newsfeed`, `${global.root_path}/config/newsfeed`, { recursive: true });
process.env.MM_MODULES_DIR = "config";
});

View File

@@ -1,17 +1,15 @@
const helpers = require("../helpers/global-setup");
const weatherFunc = require("../helpers/weather-functions");
const { cleanupMockData } = require("../../utils/weather_mocker");
describe("Weather module", () => {
afterAll(async () => {
await helpers.stopApplication();
await cleanupMockData();
await weatherFunc.stopApplication();
});
describe("Current weather", () => {
describe("Default configuration", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/currentweather_default.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/currentweather_default.js", {});
});
it("should render wind speed and wind direction", async () => {
@@ -20,12 +18,16 @@ describe("Weather module", () => {
it("should render temperature with icon", async () => {
await expect(weatherFunc.getText(".weather .large span.light.bright", "1.5°")).resolves.toBe(true);
const elem = await helpers.waitForElement(".weather .large span.weathericon");
expect(elem).not.toBeNull();
});
it("should render feels like temperature", async () => {
// Template contains &nbsp; which renders as \xa0
await expect(weatherFunc.getText(".weather .normal.medium.feelslike span.dimmed", "93.7\xa0 Feels like -5.6°")).resolves.toBe(true);
});
it("should render humidity next to feels-like", async () => {
await expect(weatherFunc.getText(".weather .normal.medium.feelslike span.dimmed .humidity", "93.7")).resolves.toBe(true);
});
@@ -34,7 +36,7 @@ describe("Weather module", () => {
describe("Compliments Integration", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/currentweather_compliments.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/currentweather_compliments.js", {});
});
it("should render a compliment based on the current weather", async () => {
@@ -44,7 +46,7 @@ describe("Weather module", () => {
describe("Configuration Options", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/currentweather_options.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/currentweather_options.js", {});
});
it("should render windUnits in beaufort", async () => {
@@ -72,7 +74,7 @@ describe("Weather module", () => {
describe("Current weather with imperial units", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/currentweather_units.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/currentweather_units.js", {});
});
it("should render wind in imperial units", async () => {

View File

@@ -1,16 +1,14 @@
const helpers = require("../helpers/global-setup");
const weatherFunc = require("../helpers/weather-functions");
const { cleanupMockData } = require("../../utils/weather_mocker");
describe("Weather module: Weather Forecast", () => {
afterAll(async () => {
await helpers.stopApplication();
await cleanupMockData();
await weatherFunc.stopApplication();
});
describe("Default configuration", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/forecastweather_default.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/forecastweather_default.js", {});
});
const days = ["Today", "Tomorrow", "Sun", "Mon", "Tue"];
@@ -54,7 +52,7 @@ describe("Weather module: Weather Forecast", () => {
describe("Absolute configuration", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/forecastweather_absolute.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/forecastweather_absolute.js", {});
});
const days = ["Fri", "Sat", "Sun", "Mon", "Tue"];
@@ -67,7 +65,7 @@ describe("Weather module: Weather Forecast", () => {
describe("Configuration Options", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/forecastweather_options.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/forecastweather_options.js", {});
});
it("should render custom table class", async () => {
@@ -94,7 +92,7 @@ describe("Weather module: Weather Forecast", () => {
describe("Forecast weather with imperial units", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/forecastweather_units.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/forecastweather_units.js", {});
});
describe("Temperature units", () => {

View File

@@ -1,16 +1,13 @@
const helpers = require("../helpers/global-setup");
const weatherFunc = require("../helpers/weather-functions");
const { cleanupMockData } = require("../../utils/weather_mocker");
describe("Weather module: Weather Hourly Forecast", () => {
afterAll(async () => {
await helpers.stopApplication();
await cleanupMockData();
await weatherFunc.stopApplication();
});
describe("Default configuration", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/hourlyweather_default.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/hourlyweather_default.js", {});
});
const minTemps = ["7:00 pm", "8:00 pm", "9:00 pm", "10:00 pm", "11:00 pm"];
@@ -23,7 +20,7 @@ describe("Weather module: Weather Hourly Forecast", () => {
describe("Hourly weather options", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/hourlyweather_options.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/hourlyweather_options.js", {});
});
describe("Hourly increments of 2", () => {
@@ -38,7 +35,7 @@ describe("Weather module: Weather Hourly Forecast", () => {
describe("Show precipitations", () => {
beforeAll(async () => {
await weatherFunc.startApp("tests/configs/modules/weather/hourlyweather_showPrecipitation.js", {});
await weatherFunc.startApplication("tests/configs/modules/weather/hourlyweather_showPrecipitation.js", {});
});
describe("Shows precipitation amount", () => {

View File

@@ -2,11 +2,17 @@ const delay = (time) => {
return new Promise((resolve) => setTimeout(resolve, time));
};
const runConfigCheck = async () => {
const serverProcess = await require("node:child_process").spawnSync("node", ["--run", "config:check"], { env: process.env });
expect(serverProcess.stderr.toString()).toBe("");
return await serverProcess.status;
};
describe("App environment", () => {
let serverProcess;
beforeAll(async () => {
process.env.MM_CONFIG_FILE = "tests/configs/default.js";
serverProcess = await require("node:child_process").spawn("npm", ["run", "server"], { env: process.env, detached: true });
serverProcess = await require("node:child_process").spawn("node", ["--run", "server"], { env: process.env, detached: true });
// we have to wait until the server is started
await delay(2000);
});
@@ -24,3 +30,15 @@ describe("App environment", () => {
expect(res.status).toBe(404);
});
});
describe("Check config", () => {
it("config check should return without errors", async () => {
process.env.MM_CONFIG_FILE = "tests/configs/default.js";
await expect(runConfigCheck()).resolves.toBe(0);
});
it("config check should fail with non existent config file", async () => {
process.env.MM_CONFIG_FILE = "tests/configs/not_exists.js";
await expect(runConfigCheck()).resolves.toBe(1);
});
});

View File

@@ -3,9 +3,26 @@ const path = require("node:path");
const helmet = require("helmet");
const { JSDOM } = require("jsdom");
const express = require("express");
const sinon = require("sinon");
const translations = require("../../translations/translations");
/**
* Helper function to create a fresh Translator instance with DOM environment.
* @returns {object} Object containing window and Translator
*/
function createTranslationTestEnvironment () {
// Setup DOM environment with Translator
const translatorJs = fs.readFileSync(path.join(__dirname, "..", "..", "js", "translator.js"), "utf-8");
const dom = new JSDOM("", { url: "http://localhost:3000", runScripts: "outside-only" });
dom.window.Log = { log: jest.fn(), error: jest.fn() };
dom.window.translations = translations;
dom.window.eval(translatorJs);
const window = dom.window;
return { window, Translator: window.Translator };
}
describe("translations", () => {
let server;
@@ -37,91 +54,76 @@ describe("translations", () => {
let dom;
beforeEach(() => {
// Create a new JSDOM instance for each test
dom = new JSDOM("", { runScripts: "dangerously", resources: "usable" });
// Create a new translation test environment for each test
const env = createTranslationTestEnvironment();
const window = env.window;
// Mock the necessary global objects
dom.window.Log = { log: jest.fn(), error: jest.fn() };
dom.window.Translator = {};
dom.window.config = { language: "de" };
// Load class.js and module.js content directly
// Load class.js and module.js content directly for loadTranslations tests
const classJs = fs.readFileSync(path.join(__dirname, "..", "..", "js", "class.js"), "utf-8");
const moduleJs = fs.readFileSync(path.join(__dirname, "..", "..", "js", "module.js"), "utf-8");
// Execute the scripts in the JSDOM context
dom.window.eval(classJs);
dom.window.eval(moduleJs);
window.eval(classJs);
window.eval(moduleJs);
// Additional setup for loadTranslations tests
window.config = { language: "de" };
dom = { window };
});
it("should load translation file", async () => {
await new Promise((resolve) => {
dom.window.onload = resolve;
});
const { Translator, Module, config } = dom.window;
config.language = "en";
Translator.load = sinon.stub().callsFake((_m, _f, _fb) => null);
Translator.load = jest.fn().mockImplementation((_m, _f, _fb) => null);
Module.register("name", { getTranslations: () => translations });
const MMM = Module.create("name");
await MMM.loadTranslations();
expect(Translator.load.args).toHaveLength(1);
expect(Translator.load.calledWith(MMM, "translations/en.json", false)).toBe(true);
expect(Translator.load.mock.calls).toHaveLength(1);
expect(Translator.load).toHaveBeenCalledWith(MMM, "translations/en.json", false);
});
it("should load translation + fallback file", async () => {
await new Promise((resolve) => {
dom.window.onload = resolve;
});
const { Translator, Module } = dom.window;
Translator.load = sinon.stub().callsFake((_m, _f, _fb) => null);
Translator.load = jest.fn().mockImplementation((_m, _f, _fb) => null);
Module.register("name", { getTranslations: () => translations });
const MMM = Module.create("name");
await MMM.loadTranslations();
expect(Translator.load.args).toHaveLength(2);
expect(Translator.load.calledWith(MMM, "translations/de.json", false)).toBe(true);
expect(Translator.load.calledWith(MMM, "translations/en.json", true)).toBe(true);
expect(Translator.load.mock.calls).toHaveLength(2);
expect(Translator.load).toHaveBeenCalledWith(MMM, "translations/de.json", false);
expect(Translator.load).toHaveBeenCalledWith(MMM, "translations/en.json", true);
});
it("should load translation fallback file", async () => {
await new Promise((resolve) => {
dom.window.onload = resolve;
});
const { Translator, Module, config } = dom.window;
config.language = "--";
Translator.load = sinon.stub().callsFake((_m, _f, _fb) => null);
Translator.load = jest.fn().mockImplementation((_m, _f, _fb) => null);
Module.register("name", { getTranslations: () => translations });
const MMM = Module.create("name");
await MMM.loadTranslations();
expect(Translator.load.args).toHaveLength(1);
expect(Translator.load.calledWith(MMM, "translations/en.json", true)).toBe(true);
expect(Translator.load.mock.calls).toHaveLength(1);
expect(Translator.load).toHaveBeenCalledWith(MMM, "translations/en.json", true);
});
it("should load no file", async () => {
await new Promise((resolve) => {
dom.window.onload = resolve;
});
const { Translator, Module } = dom.window;
Translator.load = sinon.stub();
Translator.load = jest.fn();
Module.register("name", {});
const MMM = Module.create("name");
await MMM.loadTranslations();
expect(Translator.load.callCount).toBe(0);
expect(Translator.load.mock.calls).toHaveLength(0);
});
});
@@ -132,21 +134,10 @@ describe("translations", () => {
}
};
const translatorJs = fs.readFileSync(path.join(__dirname, "..", "..", "js", "translator.js"), "utf-8");
describe("parsing language files through the Translator class", () => {
for (const language in translations) {
it(`should parse ${language}`, async () => {
const dom = new JSDOM("", { runScripts: "dangerously", resources: "usable" });
dom.window.Log = { log: jest.fn() };
dom.window.translations = translations;
dom.window.eval(translatorJs);
await new Promise((resolve) => {
dom.window.onload = resolve;
});
const { Translator } = dom.window;
const { Translator } = createTranslationTestEnvironment();
await Translator.load(mmm, translations[language], false);
expect(typeof Translator.translations[mmm.name]).toBe("object");
@@ -177,19 +168,10 @@ describe("translations", () => {
};
// Function to initialize JSDOM and load translations
const initializeTranslationDOM = (language) => {
const dom = new JSDOM("", { runScripts: "dangerously", resources: "usable" });
dom.window.Log = { log: jest.fn() };
dom.window.translations = translations;
dom.window.eval(translatorJs);
return new Promise((resolve) => {
dom.window.onload = async () => {
const { Translator } = dom.window;
await Translator.load(mmm, translations[language], false);
resolve(Translator.translations[mmm.name]);
};
});
const initializeTranslationDOM = async (language) => {
const { Translator } = createTranslationTestEnvironment();
await Translator.load(mmm, translations[language], false);
return Translator.translations[mmm.name];
};
beforeAll(async () => {

View File

@@ -9,7 +9,7 @@ describe("Vendors", () => {
});
describe("Get list vendors", () => {
const vendors = require(`${__dirname}/../../js/vendor.js`);
const vendors = require(`${global.root_path}/js/vendor.js`);
Object.keys(vendors).forEach((vendor) => {
it(`should return 200 HTTP code for vendor "${vendor}"`, async () => {

View File

@@ -2,29 +2,38 @@ const helpers = require("../helpers/global-setup");
const weatherHelper = require("../helpers/weather-setup");
const { cleanupMockData } = require("../../utils/weather_mocker");
const CURRENT_WEATHER_CONFIG = "tests/configs/modules/weather/currentweather_default.js";
const SUNRISE_DATE = "13 Jan 2019 00:30:00 GMT";
const SUNSET_DATE = "13 Jan 2019 12:30:00 GMT";
const SUN_EVENT_SELECTOR = ".weather .normal.medium span:nth-child(4)";
const EXPECTED_SUNRISE_TEXT = "7:00 am";
const EXPECTED_SUNSET_TEXT = "3:45 pm";
describe("Weather module", () => {
afterEach(async () => {
await helpers.stopApplication();
await cleanupMockData();
cleanupMockData();
});
describe("Current weather with sunrise", () => {
beforeAll(async () => {
await weatherHelper.startApp("tests/configs/modules/weather/currentweather_default.js", "13 Jan 2019 00:30:00 GMT");
await weatherHelper.startApp(CURRENT_WEATHER_CONFIG, SUNRISE_DATE);
});
it("should render sunrise", async () => {
await expect(weatherHelper.getText(".weather .normal.medium span:nth-child(4)", "7:00 am")).resolves.toBe(true);
const isSunriseRendered = await weatherHelper.getText(SUN_EVENT_SELECTOR, EXPECTED_SUNRISE_TEXT);
expect(isSunriseRendered).toBe(true);
});
});
describe("Current weather with sunset", () => {
beforeAll(async () => {
await weatherHelper.startApp("tests/configs/modules/weather/currentweather_default.js", "13 Jan 2019 12:30:00 GMT");
await weatherHelper.startApp(CURRENT_WEATHER_CONFIG, SUNSET_DATE);
});
it("should render sunset", async () => {
await expect(weatherHelper.getText(".weather .normal.medium span:nth-child(4)", "3:45 pm")).resolves.toBe(true);
const isSunsetRendered = await weatherHelper.getText(SUN_EVENT_SELECTOR, EXPECTED_SUNSET_TEXT);
expect(isSunsetRendered).toBe(true);
});
});
});

View File

@@ -4,11 +4,23 @@ const helmet = require("helmet");
const { JSDOM } = require("jsdom");
const express = require("express");
/**
* Helper function to create a fresh Translator instance with DOM environment.
* @returns {object} Object containing window and Translator
*/
function createTranslationTestEnvironment () {
const translatorJs = fs.readFileSync(path.join(__dirname, "..", "..", "..", "js", "translator.js"), "utf-8");
const dom = new JSDOM("", { url: "http://localhost:3001", runScripts: "outside-only" });
dom.window.Log = { log: jest.fn(), error: jest.fn() };
dom.window.eval(translatorJs);
return { window: dom.window, Translator: dom.window.Translator };
}
describe("Translator", () => {
let server;
const sockets = new Set();
const translatorJsPath = path.join(__dirname, "..", "..", "..", "js", "translator.js");
const translatorJsScriptContent = fs.readFileSync(translatorJsPath, "utf8");
const translationTestData = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "..", "tests", "mocks", "translation_test.json"), "utf8"));
beforeAll(() => {
@@ -20,7 +32,7 @@ describe("Translator", () => {
});
app.use("/translations", express.static(path.join(__dirname, "..", "..", "..", "tests", "mocks")));
server = app.listen(3000);
server = app.listen(3001);
server.on("connection", (socket) => {
sockets.add(socket);
@@ -81,12 +93,7 @@ describe("Translator", () => {
};
it("should return custom module translation", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { Translator } = createTranslationTestEnvironment();
setTranslations(Translator);
let translation = Translator.translate({ name: "MMM-Module" }, "Hello");
@@ -97,12 +104,7 @@ describe("Translator", () => {
});
it("should return core translation", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { Translator } = createTranslationTestEnvironment();
setTranslations(Translator);
let translation = Translator.translate({ name: "MMM-Module" }, "FOO");
expect(translation).toBe("Foo");
@@ -111,48 +113,28 @@ describe("Translator", () => {
});
it("should return custom module translation fallback", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { Translator } = createTranslationTestEnvironment();
setTranslations(Translator);
const translation = Translator.translate({ name: "MMM-Module" }, "A key");
expect(translation).toBe("A translation");
});
it("should return core translation fallback", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { Translator } = createTranslationTestEnvironment();
setTranslations(Translator);
const translation = Translator.translate({ name: "MMM-Module" }, "Fallback");
expect(translation).toBe("core fallback");
});
it("should return translation with placeholder for missing variables", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { Translator } = createTranslationTestEnvironment();
setTranslations(Translator);
const translation = Translator.translate({ name: "MMM-Module" }, "Hello {username}");
expect(translation).toBe("Hallo {username}");
});
it("should return key if no translation was found", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { Translator } = createTranslationTestEnvironment();
setTranslations(Translator);
const translation = Translator.translate({ name: "MMM-Module" }, "MISSING");
expect(translation).toBe("MISSING");
@@ -163,17 +145,12 @@ describe("Translator", () => {
const mmm = {
name: "TranslationTest",
file (file) {
return `http://localhost:3000/translations/${file}`;
return `http://localhost:3001/translations/${file}`;
}
};
it("should load translations", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
dom.window.Log = { log: jest.fn() };
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { Translator } = createTranslationTestEnvironment();
const file = "translation_test.json";
await Translator.load(mmm, file, false);
@@ -182,30 +159,18 @@ describe("Translator", () => {
});
it("should load translation fallbacks", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { Translator } = createTranslationTestEnvironment();
const file = "translation_test.json";
dom.window.Log = { log: jest.fn() };
await Translator.load(mmm, file, true);
const json = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "..", "tests", "mocks", file), "utf8"));
expect(Translator.translationsFallback[mmm.name]).toEqual(json);
});
it("should not load translations, if module fallback exists", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { Translator } = createTranslationTestEnvironment();
const file = "translation_test.json";
dom.window.Log = { log: jest.fn() };
Translator.translationsFallback[mmm.name] = {
Hello: "Hallo"
};
@@ -220,37 +185,23 @@ describe("Translator", () => {
describe("loadCoreTranslations", () => {
it("should load core translations and fallback", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
dom.window.translations = { en: "http://localhost:3000/translations/translation_test.json" };
dom.window.Log = { log: jest.fn() };
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { window, Translator } = createTranslationTestEnvironment();
window.translations = { en: "http://localhost:3001/translations/translation_test.json" };
await Translator.loadCoreTranslations("en");
const en = translationTestData;
await new Promise((resolve) => setTimeout(resolve, 500));
expect(Translator.coreTranslations).toEqual(en);
expect(Translator.coreTranslationsFallback).toEqual(en);
});
it("should load core fallback if language cannot be found", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
dom.window.translations = { en: "http://localhost:3000/translations/translation_test.json" };
dom.window.Log = { log: jest.fn() };
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { window, Translator } = createTranslationTestEnvironment();
window.translations = { en: "http://localhost:3001/translations/translation_test.json" };
await Translator.loadCoreTranslations("MISSINGLANG");
const en = translationTestData;
await new Promise((resolve) => setTimeout(resolve, 500));
expect(Translator.coreTranslations).toEqual({});
expect(Translator.coreTranslationsFallback).toEqual(en);
});
@@ -258,35 +209,20 @@ describe("Translator", () => {
describe("loadCoreTranslationsFallback", () => {
it("should load core translations fallback", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
dom.window.translations = { en: "http://localhost:3000/translations/translation_test.json" };
dom.window.Log = { log: jest.fn() };
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { window, Translator } = createTranslationTestEnvironment();
window.translations = { en: "http://localhost:3001/translations/translation_test.json" };
await Translator.loadCoreTranslationsFallback();
const en = translationTestData;
await new Promise((resolve) => setTimeout(resolve, 500));
expect(Translator.coreTranslationsFallback).toEqual(en);
});
it("should load core fallback if language cannot be found", async () => {
const dom = new JSDOM("", { runScripts: "outside-only" });
dom.window.eval(translatorJsScriptContent);
dom.window.translations = {};
dom.window.Log = { log: jest.fn() };
await new Promise((resolve) => dom.window.onload = resolve);
const { Translator } = dom.window;
const { window, Translator } = createTranslationTestEnvironment();
window.translations = {};
await Translator.loadCoreTranslations();
await new Promise((resolve) => setTimeout(resolve, 500));
expect(Translator.coreTranslationsFallback).toEqual({});
});
});

View File

@@ -1,4 +1,4 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
exports[`Updatenotification custom module returns status information without hash 1`] = `
{

View File

@@ -1,4 +1,5 @@
const { cors } = require("../../../js/server_functions");
const { expect } = require("playwright/test");
const { cors, getUserAgent } = require("#server_functions");
describe("server_functions tests", () => {
describe("The cors method", () => {
@@ -142,5 +143,21 @@ describe("server_functions tests", () => {
expect(corsResponse.set.mock.calls[2][0]).toBe("header2");
expect(corsResponse.set.mock.calls[2][1]).toBe("value2");
});
it("Gets User-Agent from configuration", async () => {
config = {};
let userAgent;
userAgent = getUserAgent();
expect(userAgent).toContain("Mozilla/5.0 (Node.js ");
config.userAgent = "Mozilla/5.0 (Foo)";
userAgent = getUserAgent();
expect(userAgent).toBe("Mozilla/5.0 (Foo)");
config.userAgent = () => "Mozilla/5.0 (Bar)";
userAgent = getUserAgent();
expect(userAgent).toBe("Mozilla/5.0 (Bar)");
});
});
});

View File

@@ -4,7 +4,7 @@ const path = require("node:path");
const root_path = path.join(__dirname, "../../..");
describe("Default modules set in modules/default/defaultmodules.js", () => {
const expectedDefaultModules = require("../../../modules/default/defaultmodules");
const expectedDefaultModules = require(`${root_path}/modules/default/defaultmodules`);
for (const defaultModule of expectedDefaultModules) {
it(`contains a folder for modules/default/${defaultModule}"`, () => {

View File

@@ -2,7 +2,7 @@ const fs = require("node:fs");
const path = require("node:path");
const root_path = path.join(__dirname, "../../..");
const version = require(`${__dirname}/../../../package.json`).version;
const version = require(`${root_path}/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"];

View File

@@ -10,7 +10,7 @@ describe("Calendar fetcher utils test", () => {
excludedEvents: [],
includePastEvents: false,
maximumEntries: 10,
maximumNumberOfDays: 365
maximumNumberOfDays: 367
};
describe("filterEvents", () => {

View File

@@ -2,10 +2,18 @@ const weather = require("../../../../../modules/default/weather/weatherutils");
const WeatherUtils = require("../../../../../modules/default/weather/weatherutils");
describe("Weather utils tests", () => {
describe("windspeed conversion to imperial", () => {
describe("temperature conversion to imperial", () => {
it("should convert temp correctly from Celsius to Celsius", () => {
expect(Math.round(WeatherUtils.convertTemp(10, "metric"))).toBe(10);
});
it("should convert temp correctly from Celsius to Fahrenheit", () => {
expect(Math.round(WeatherUtils.convertTemp(10, "imperial"))).toBe(50);
});
it("should convert temp correctly from Fahrenheit to Celsius", () => {
expect(Math.round(WeatherUtils.convertTempToMetric(10))).toBe(-12);
});
});
describe("windspeed conversion to beaufort", () => {
@@ -44,11 +52,11 @@ describe("Weather utils tests", () => {
describe("feelsLike calculation", () => {
it("should return a calculated feelsLike info (negative value)", () => {
expect(WeatherUtils.calculateFeelsLike(0, 20, 40)).toBe(-9.444444444444445);
expect(WeatherUtils.calculateFeelsLike(0, 20, 40)).toBe(-9.397005931555448);
});
it("should return a calculated feelsLike info (positive value)", () => {
expect(WeatherUtils.calculateFeelsLike(30, 0, 60)).toBe(32.8320322777777);
expect(WeatherUtils.calculateFeelsLike(30, 0, 60)).toBe(32.832032277777756);
});
});

View File

@@ -1,7 +1,6 @@
const fs = require("node:fs");
const path = require("node:path");
const util = require("node:util");
const exec = util.promisify(require("node:child_process").exec);
const exec = require("node:child_process").execSync;
/**
* @param {string} type what data to read, can be "current" "forecast" or "hourly
@@ -45,9 +44,9 @@ const injectMockData = (configFileName, extendedData = {}) => {
return tempFile;
};
const cleanupMockData = async () => {
const cleanupMockData = () => {
const tempDir = path.resolve(`${__dirname}/../configs`).toString();
await exec(`find ${tempDir} -type f -name *_temp.js -delete`);
exec(`find ${tempDir} -type f -name *_temp.js -delete`);
};
module.exports = { injectMockData, cleanupMockData };