treker-po-trenirovkam-i-pit.../tests/registration-plan.test.mjs

91 lines
4.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// TPTIP-95: кнопка «Создать меню и план тренировок» на экране регистрации показывает результат по дням.
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { JSDOM } from 'jsdom';
import { nutrition } from '../profile/nutrition.mjs';
const require = createRequire(import.meta.url);
const GymPlan = require('../gym-plan.i18n.js');
const translations = JSON.parse(readFileSync(new URL('../profile/i18n.json', import.meta.url), 'utf8'));
// The module imports are replaced with globals so that jsdom can run the page script.
const appSource = readFileSync(new URL('../profile/app.js', import.meta.url), 'utf8')
.replace(/^import .*$/gm, '');
async function openRegistration() {
const dom = new JSDOM('<!doctype html><html><body><main id="app"></main></body></html>', {
url: 'http://localhost/?lang=ru', runScripts: 'outside-only', pretendToBeVisual: true,
});
const w = dom.window;
Object.assign(w, {
GymPlan, nutrition, initTelemetry: async () => {}, scrollTo: () => {},
fetch: async path => path === '/profile/i18n.json'
? { ok: true, json: async () => translations }
: { ok: false, status: 401, json: async () => ({ error: 'signin' }) },
});
w.sessionStorage.setItem('tpt.welcomeSeen', '1');
w.eval(`window.__ready = (async () => {\n${appSource}\n})();`);
await w.__ready;
const document = w.document;
const toRegister = [...document.querySelectorAll('button')].find(b => b.textContent === translations.ru.toRegister);
toRegister.click();
return { w, document };
}
function fill(w, document, values) {
for (const [name, value] of Object.entries(values)) {
const input = document.querySelector(`[data-auth-form] [name=${name}]`);
input.value = value;
input.dispatchEvent(new w.Event('input', { bubbles: true }));
}
}
const openPlan = document => document.querySelector('[data-goal-plan-open]').click();
const days = document => [...document.querySelectorAll('#goal-plan-content [data-goal-plan-day]')];
const measurements = { height: '175', weight: '75', age: '30', sex: 'male', activity: '1.375' };
test('Не хватает данных: сообщение и перечень полей вместо пустого результата', async () => {
const { w, document } = await openRegistration();
fill(w, document, { weight: '75', age: '30', activity: '1.375' });
openPlan(document);
const content = document.querySelector('#goal-plan-content');
assert.equal(content.hidden, false);
const missing = content.querySelector('[data-goal-plan-missing]').textContent;
assert.match(missing, /Заполните возраст, рост, вес, пол, активность и цель — тогда здесь появятся меню и план по дням\./);
assert.match(missing, /Рост не заполнен\. Введите число от 100 до 250 см\./);
assert.match(missing, /Пол не выбран\. Выберите вариант для расчёта\./);
assert.doesNotMatch(missing, /Вес|Возраст не/);
assert.equal(days(document).length, 0);
});
test('Результат по введённым данным: четыре дня с блюдами и упражнениями', async () => {
const { w, document } = await openRegistration();
fill(w, document, { ...measurements, goal: 'lose' });
openPlan(document);
const list = days(document);
assert.equal(list.length, 4);
for (const day of list) {
assert.match(day.textContent, /Пример меню/);
assert.match(day.textContent, /Упражнения/);
assert.match(day.textContent, /\d+ г/);
}
assert.match(list[0].textContent, /Жим гантелей лёжа — 2 × 10/);
assert.equal(document.querySelector('[data-goal-plan-missing]'), null);
});
test('Другая цель даёт другой результат, а изменение данных скрывает прежний', async () => {
const { w, document } = await openRegistration();
fill(w, document, { ...measurements, goal: 'lose' });
openPlan(document);
const before = days(document).map(day => day.textContent);
fill(w, document, { goal: 'gain' });
assert.equal(document.querySelector('#goal-plan-content').hidden, true);
openPlan(document);
const after = days(document).map(day => day.textContent);
assert.equal(after.length, 4);
assert.match(after[0], /Жим гантелей лёжа — 4 × 10/);
const breakfast = text => Number(text.match(/овсянка с йогуртом[^·]*· (\d+)/)[1]);
assert.ok(breakfast(after[0]) > breakfast(before[0]));
assert.notDeepEqual(after, before);
});