Files
portifolio-evandrodevbr/lib/device.paths.test.ts
T
Evandro Fonseca Junior c9a0b80656 perf(movimento): uma transição, 3D leve e vídeo certo por aparelho
Passagens com fade e 32 px, cena anterior termina em opacidade 0, sem visibility nem clip-path. 3D do hero como fundo ambiente, sob demanda e desligado em toque, aparelho fraco, saveData e movimento reduzido. Lenis fora do toque e salto direto em âncoras distantes. Vitrine só de clientes, até 3 capítulos, fixa só no desktop e carrossel no celular; vídeo só do projeto em cena com preload metadata. Rótulos mono a partir de 12 px e limão só no contato.
2026-10-14 03:32:23 -03:00

186 lines
5.8 KiB
TypeScript

import { readFileSync } from "node:fs";
import { join } from "node:path";
import ts from "typescript";
import {
isCoarsePointer,
isLowPowerDevice,
isMobileViewport,
isSaveData,
prefersReducedMotion,
} from "./device";
/**
* Testes de caminhos-base de lib/device.ts (complemento de device.test.ts): matches() sem matchMedia,
* cada condição de isLowPowerDevice isolada (inclusive os limites), isSaveData e o ambiente sem window/navigator
* (servidor). O servidor é simulado transpilando o fonte e executando-o com `window` e `navigator` indefinidos,
* porque o jsdom não deixa esconder esses globais.
*/
type DeviceModule = typeof import("./device");
const originalMatchMedia = window.matchMedia;
function mockMedia(active: string[]) {
window.matchMedia = jest.fn().mockImplementation((query: string) => ({
matches: active.includes(query),
media: query,
addEventListener() {},
removeEventListener() {},
}));
}
function mockNavigator(values: Record<string, unknown>) {
for (const [key, value] of Object.entries(values))
Object.defineProperty(navigator, key, { configurable: true, value });
}
function loadOnServer(globals: { window?: unknown; navigator?: unknown }) {
const source = readFileSync(join(process.cwd(), "lib/device.ts"), "utf8");
const { outputText } = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS },
});
const loaded = { exports: {} as DeviceModule };
new Function("module", "exports", "window", "navigator", outputText)(
loaded,
loaded.exports,
globals.window,
globals.navigator,
);
return loaded.exports;
}
beforeEach(() => {
mockMedia([]);
mockNavigator({
hardwareConcurrency: 8,
deviceMemory: undefined,
connection: undefined,
});
});
afterEach(() => {
window.matchMedia = originalMatchMedia;
});
describe("matches() (through the media helpers)", () => {
it("path: matchMedia is not available -> every media hint is false", () => {
// @ts-expect-error simula um navegador sem matchMedia
window.matchMedia = undefined;
expect(isCoarsePointer()).toBe(false);
expect(prefersReducedMotion()).toBe(false);
expect(isMobileViewport()).toBe(false);
expect(isLowPowerDevice()).toBe(false);
});
it("path: matchMedia answers false for the query -> false", () => {
expect(isCoarsePointer()).toBe(false);
});
it("path: matchMedia answers true only for the asked query -> only that hint is true", () => {
mockMedia(["(prefers-reduced-motion: reduce)"]);
expect(prefersReducedMotion()).toBe(true);
expect(isCoarsePointer()).toBe(false);
expect(isMobileViewport()).toBe(false);
});
});
describe("isSaveData()", () => {
it.each([
["connection is missing", undefined],
["connection has no saveData", {}],
["saveData is false", { saveData: false }],
["saveData is a truthy non-boolean", { saveData: "true" }],
])("path: %s -> false", (_label, connection) => {
mockNavigator({ connection });
expect(isSaveData()).toBe(false);
});
it("path: saveData is exactly true -> true", () => {
mockNavigator({ connection: { saveData: true } });
expect(isSaveData()).toBe(true);
});
});
describe("isLowPowerDevice(): limites de cada condição, uma de cada vez", () => {
it.each([
["5 cores", { hardwareConcurrency: 5 }],
["8 GB of memory", { hardwareConcurrency: 8, deviceMemory: 8 }],
["5 GB of memory", { hardwareConcurrency: 8, deviceMemory: 5 }],
["cores reported as text", { hardwareConcurrency: "2" }],
["memory reported as text", { deviceMemory: "2" }],
["cores reported as null", { hardwareConcurrency: null }],
])(
"path: %s -> full power (just above the limit or not a number)",
(_label, hints) => {
mockNavigator(hints);
expect(isLowPowerDevice()).toBe(false);
},
);
it.each([
["exactly 4 cores", { hardwareConcurrency: 4 }],
["exactly 4 GB", { deviceMemory: 4 }],
["0.5 GB", { deviceMemory: 0.5 }],
["1 core", { hardwareConcurrency: 1 }],
])("path: %s -> low power", (_label, hints) => {
mockNavigator(hints);
expect(isLowPowerDevice()).toBe(true);
});
it("path: only the first condition is true (touch) -> low power without reading the rest", () => {
mockMedia(["(pointer: coarse)"]);
mockNavigator({ hardwareConcurrency: 16, deviceMemory: 16 });
expect(isLowPowerDevice()).toBe(true);
});
it("path: several conditions true at once -> still just true", () => {
mockMedia(["(pointer: coarse)", "(prefers-reduced-motion: reduce)"]);
mockNavigator({
hardwareConcurrency: 2,
deviceMemory: 2,
connection: { saveData: true },
});
expect(isLowPowerDevice()).toBe(true);
});
});
describe("without window and navigator (server)", () => {
it("path: no window -> media hints are false", () => {
const device = loadOnServer({ window: undefined, navigator: undefined });
expect(device.isCoarsePointer()).toBe(false);
expect(device.prefersReducedMotion()).toBe(false);
expect(device.isMobileViewport()).toBe(false);
});
it("path: no navigator -> save data is off and the device counts as low power", () => {
const device = loadOnServer({ window: undefined, navigator: undefined });
expect(device.isSaveData()).toBe(false);
expect(device.isLowPowerDevice()).toBe(true);
});
it("path: a navigator without window (runtime that exposes only navigator) -> hints still read", () => {
const device = loadOnServer({
window: undefined,
navigator: { hardwareConcurrency: 16, connection: { saveData: true } },
});
expect(device.isSaveData()).toBe(true);
expect(device.isLowPowerDevice()).toBe(true);
const capable = loadOnServer({
window: undefined,
navigator: { hardwareConcurrency: 16 },
});
expect(capable.isLowPowerDevice()).toBe(false);
});
});