293 lines
12 KiB
JavaScript
293 lines
12 KiB
JavaScript
'use strict';
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const vm = require('vm');
|
|
|
|
// A small DOM/media fixture verifies lifecycle behavior without launching the app
|
|
// or touching the gym's database. Actual Safari decoding still needs an iPad run.
|
|
function eventTarget(target = {}) {
|
|
const listeners = new Map();
|
|
target.addEventListener = (type, callback) => {
|
|
if (!listeners.has(type)) listeners.set(type, []);
|
|
listeners.get(type).push(callback);
|
|
};
|
|
target.dispatch = (type, event = {}) => {
|
|
for (const callback of listeners.get(type) || []) callback(event);
|
|
};
|
|
return target;
|
|
}
|
|
|
|
function setup(search = '?id=1') {
|
|
const videos = [];
|
|
class Element {
|
|
constructor(tagName) {
|
|
eventTarget(this);
|
|
this.tagName = tagName;
|
|
this.children = [];
|
|
this.attributes = {};
|
|
this.hidden = false;
|
|
this.classList = { toggle: jest.fn() };
|
|
if (tagName === 'video') {
|
|
videos.push(this);
|
|
this.currentTime = 0;
|
|
this.paused = true;
|
|
this.play = jest.fn(() => {
|
|
this.paused = false;
|
|
return Promise.resolve();
|
|
});
|
|
this.pause = jest.fn(() => { this.paused = true; });
|
|
this.load = jest.fn(() => { this.currentTime = 0; this.error = null; });
|
|
}
|
|
}
|
|
append(...children) {
|
|
for (const child of children) {
|
|
this.children.push(child);
|
|
child.parentNode = this;
|
|
}
|
|
}
|
|
appendChild(child) { this.append(child); }
|
|
remove() {
|
|
if (!this.parentNode) return;
|
|
const parent = this.parentNode;
|
|
parent.children.splice(parent.children.indexOf(this), 1);
|
|
this.parentNode = null;
|
|
}
|
|
replaceWith(replacement) {
|
|
const parent = this.parentNode;
|
|
parent.children[parent.children.indexOf(this)] = replacement;
|
|
replacement.parentNode = parent;
|
|
this.parentNode = null;
|
|
}
|
|
replaceChildren() { this.children.slice().forEach(child => child.remove()); }
|
|
set innerHTML(value) { this.replaceChildren(); this.html = value; }
|
|
setAttribute(key, value) { this.attributes[key] = value; }
|
|
removeAttribute(key) {
|
|
delete this.attributes[key];
|
|
if (key === 'src') this.src = '';
|
|
}
|
|
}
|
|
const grid = new Element('div');
|
|
const banner = new Element('div');
|
|
const document = eventTarget({
|
|
hidden: false,
|
|
body: new Element('body'),
|
|
createElement: tag => new Element(tag),
|
|
getElementById: id => ({ 'display-video-grid': grid, 'display-offline-banner': banner })[id],
|
|
});
|
|
const window = eventTarget({ location: { search, href: `https://vitfit.test/workout-display.html${search}` } });
|
|
const auth = { jwt: 'test-token', org: { id: 3 } };
|
|
const Api = { fetch: jest.fn() };
|
|
const context = vm.createContext({
|
|
document, window, URL, URLSearchParams, Date, AbortController,
|
|
setInterval, clearInterval, setTimeout, clearTimeout,
|
|
Auth: { getJwt: () => auth.jwt, getSelectedOrg: () => auth.org },
|
|
Branding: { apply: jest.fn() }, Api,
|
|
fetch: jest.fn(() => Promise.resolve({ ok: false })),
|
|
});
|
|
const source = fs.readFileSync(path.join(__dirname, '../../public/js/display.js'), 'utf8');
|
|
vm.runInContext(`${source}\nglobalThis.display = Display;`, context);
|
|
const workout = { videos: [1, 2, 3, 4].map(id => ({ video: { streamUrl: `/api/v1/videos/stream/${id}.mp4` }, reps: 10 })) };
|
|
return { context, display: context.display, document, window, grid, videos, auth, workout, Api, banner };
|
|
}
|
|
|
|
beforeEach(() => { jest.useFakeTimers(); jest.setSystemTime(100000); });
|
|
afterEach(() => { jest.clearAllTimers(); jest.useRealTimers(); });
|
|
|
|
test('12 simulated hours of polling and looping retain four players and one watchdog', () => {
|
|
const { display, workout, videos, grid } = setup();
|
|
display.renderWorkout(workout);
|
|
const originals = [...videos];
|
|
for (let tick = 1; tick <= 8640; tick++) {
|
|
for (const video of videos) {
|
|
video.currentTime = tick % 8; // include wraparound at each loop boundary
|
|
video.dispatch('timeupdate');
|
|
}
|
|
jest.advanceTimersByTime(5000);
|
|
if (tick % 6 === 0) display.renderWorkout(workout);
|
|
}
|
|
expect(videos).toEqual(originals);
|
|
expect(grid.children).toHaveLength(4);
|
|
for (const video of videos) {
|
|
expect(video.load).not.toHaveBeenCalled();
|
|
expect(video.play).toHaveBeenCalledTimes(1);
|
|
}
|
|
expect(jest.getTimerCount()).toBe(1);
|
|
});
|
|
|
|
test('changing repetitions preserves every video and changing one source releases only that player', () => {
|
|
const { display, workout, videos, grid } = setup();
|
|
display.renderWorkout(workout);
|
|
workout.videos[0].reps = 20;
|
|
display.renderWorkout(workout);
|
|
expect(videos).toHaveLength(4);
|
|
expect(grid.children[0].children.at(-1).textContent).toBe('20');
|
|
const old = videos[1];
|
|
workout.videos[1].video.streamUrl = '/api/v1/videos/stream/new.mp4';
|
|
display.renderWorkout(workout);
|
|
expect(videos).toHaveLength(5);
|
|
expect(old.pause).toHaveBeenCalledTimes(1);
|
|
expect(old.load).toHaveBeenCalledTimes(1);
|
|
expect(old.src).toBe('');
|
|
expect(videos[0].load).not.toHaveBeenCalled();
|
|
expect(grid.children).toHaveLength(4);
|
|
});
|
|
|
|
test('a stalled player recovers while progressing players stay loaded, with bounded retries', () => {
|
|
const { display, workout, videos } = setup();
|
|
display.renderWorkout(workout);
|
|
for (let tick = 1; tick <= 60; tick++) {
|
|
for (const video of videos.slice(1)) {
|
|
video.currentTime = tick;
|
|
video.dispatch('timeupdate');
|
|
}
|
|
jest.advanceTimersByTime(5000);
|
|
}
|
|
// 20s, 40s, 80s, 160s: the next attempt waits until 320s.
|
|
expect(videos[0].load).toHaveBeenCalledTimes(8);
|
|
for (const video of videos.slice(1)) expect(video.load).not.toHaveBeenCalled();
|
|
expect(jest.getTimerCount()).toBe(1);
|
|
});
|
|
|
|
test('Safari autoplay denial offers a tap and suppresses automatic reloads', async () => {
|
|
const { display, workout, videos, grid } = setup();
|
|
display.renderWorkout(workout);
|
|
const video = videos[0];
|
|
video.play.mockRejectedValueOnce(Object.assign(new Error('Gesture required'), { name: 'NotAllowedError' }));
|
|
video.paused = true;
|
|
jest.advanceTimersByTime(20000);
|
|
await Promise.resolve();
|
|
const resume = grid.children[0].children[1];
|
|
expect(resume.hidden).toBe(false);
|
|
jest.advanceTimersByTime(600000);
|
|
expect(video.load).not.toHaveBeenCalled();
|
|
resume.dispatch('click');
|
|
expect(resume.hidden).toBe(true);
|
|
expect(video.play).toHaveBeenCalledTimes(3);
|
|
});
|
|
|
|
test('hidden pages pause playback and returning pages resume without reloading', () => {
|
|
const { display, workout, videos, document } = setup();
|
|
display.renderWorkout(workout);
|
|
document.hidden = true;
|
|
document.dispatch('visibilitychange');
|
|
jest.advanceTimersByTime(600000);
|
|
for (const video of videos) {
|
|
expect(video.pause).toHaveBeenCalledTimes(1);
|
|
expect(video.load).not.toHaveBeenCalled();
|
|
}
|
|
document.hidden = false;
|
|
document.dispatch('visibilitychange');
|
|
for (const video of videos) expect(video.play).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
test('empty workouts and navigation release resources; back navigation restores playback', () => {
|
|
const { display, workout, videos, window, grid } = setup();
|
|
display.renderWorkout(workout);
|
|
window.dispatch('pagehide');
|
|
expect(jest.getTimerCount()).toBe(0);
|
|
for (const video of videos) expect(video.src).toBe('');
|
|
window.dispatch('pageshow', { persisted: true });
|
|
expect(grid.children).toHaveLength(4);
|
|
expect(videos).toHaveLength(8);
|
|
expect(jest.getTimerCount()).toBe(1);
|
|
display.renderWorkout({ videos: [] });
|
|
expect(grid.children).toHaveLength(0);
|
|
expect(grid.html).toContain('No exercises assigned');
|
|
expect(jest.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
test('stream URLs preserve query parameters, scope and refreshed authentication', () => {
|
|
const { display, workout, videos, auth } = setup();
|
|
workout.videos[0].video.streamUrl += '?quality=small';
|
|
display.renderWorkout(workout);
|
|
const url = new URL(videos[0].src);
|
|
expect(url.searchParams.get('quality')).toBe('small');
|
|
expect(url.searchParams.get('orgId')).toBe('3');
|
|
expect(url.searchParams.get('token')).toBe('test-token');
|
|
expect(videos[0].disableRemotePlayback).toBe(true);
|
|
expect(videos[0].attributes['x-webkit-airplay']).toBe('deny');
|
|
auth.jwt = 'refreshed-token';
|
|
display.renderWorkout(workout);
|
|
expect(new URL(videos[4].src).searchParams.get('token')).toBe('refreshed-token');
|
|
expect(videos[0].src).toBe('');
|
|
});
|
|
|
|
test('polling keeps last data on errors, clears the banner on recovery and never overlaps', async () => {
|
|
const fixture = setup();
|
|
const { context, document, Api, workout, banner, window } = fixture;
|
|
const html = fs.readFileSync(path.join(__dirname, '../../public/workout-display.html'), 'utf8');
|
|
const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
|
|
let finish;
|
|
Api.fetch.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
|
|
vm.runInContext(script, context);
|
|
document.dispatch('DOMContentLoaded');
|
|
jest.advanceTimersByTime(60000);
|
|
expect(Api.fetch).toHaveBeenCalledTimes(1);
|
|
finish({ ok: false });
|
|
await jest.advanceTimersByTimeAsync(0);
|
|
expect(banner.classList.toggle).toHaveBeenLastCalledWith('visible', true);
|
|
Api.fetch.mockResolvedValue({ ok: true, json: async () => ({ data: workout }) });
|
|
await jest.advanceTimersByTimeAsync(30000);
|
|
expect(Api.fetch).toHaveBeenCalledTimes(2);
|
|
expect(banner.classList.toggle).toHaveBeenLastCalledWith('visible', false);
|
|
expect(fixture.videos).toHaveLength(4);
|
|
window.dispatch('pagehide');
|
|
expect(jest.getTimerCount()).toBe(0);
|
|
window.dispatch('pageshow', { persisted: true });
|
|
await jest.advanceTimersByTimeAsync(0);
|
|
expect(Api.fetch).toHaveBeenCalledTimes(3);
|
|
});
|
|
|
|
test('the poll deadline aborts a hung request and permits the next refresh', async () => {
|
|
const { context, document, Api, workout, banner } = setup();
|
|
const html = fs.readFileSync(path.join(__dirname, '../../public/workout-display.html'), 'utf8');
|
|
Api.fetch.mockImplementationOnce((url, { signal }) => new Promise((resolve, reject) => {
|
|
signal.addEventListener('abort', () => reject(new Error('Aborted')));
|
|
}));
|
|
Api.fetch.mockResolvedValue({ ok: true, json: async () => ({ data: workout }) });
|
|
vm.runInContext(html.match(/<script>([\s\S]*?)<\/script>/)[1], context);
|
|
document.dispatch('DOMContentLoaded');
|
|
await jest.advanceTimersByTimeAsync(15000);
|
|
expect(banner.classList.toggle).toHaveBeenLastCalledWith('visible', true);
|
|
await jest.advanceTimersByTimeAsync(30000);
|
|
expect(Api.fetch).toHaveBeenCalledTimes(2);
|
|
expect(banner.classList.toggle).toHaveBeenLastCalledWith('visible', false);
|
|
});
|
|
|
|
test('authentication requests share the poll deadline; an aborted login retains the session', async () => {
|
|
const { context } = setup();
|
|
const items = new Map([
|
|
['vf_jwt', 'session-token'], ['vf_device', 'device-token'],
|
|
]);
|
|
context.localStorage = {
|
|
getItem: key => items.get(key) || null,
|
|
setItem: (key, value) => items.set(key, value),
|
|
removeItem: key => items.delete(key),
|
|
};
|
|
context.FormData = class {};
|
|
context.atob = () => JSON.stringify({ exp: (Date.now() + 1000) / 1000 });
|
|
const controller = new AbortController();
|
|
let loginStarted;
|
|
const started = new Promise(resolve => { loginStarted = resolve; });
|
|
context.fetch = jest.fn(async (url, options) => {
|
|
expect(options.signal).toBe(controller.signal);
|
|
if (url.endsWith('/refresh-token')) return { ok: false };
|
|
if (url.endsWith('/device-login')) {
|
|
loginStarted();
|
|
return new Promise((resolve, reject) => {
|
|
options.signal.addEventListener('abort', () => reject(new Error('Aborted')));
|
|
});
|
|
}
|
|
return { status: 401 };
|
|
});
|
|
const core = fs.readFileSync(path.join(__dirname, '../../public/js/core.js'), 'utf8');
|
|
vm.runInContext(`${core}\nglobalThis.coreApi = Api;`, context);
|
|
const request = context.coreApi.fetch('/api/v1/workouts/1', { signal: controller.signal });
|
|
await started;
|
|
controller.abort(new Error('Deadline reached'));
|
|
await expect(request).rejects.toThrow('Deadline reached');
|
|
expect(items.get('vf_jwt')).toBe('session-token');
|
|
expect(items.get('vf_device')).toBe('device-token');
|
|
});
|