Files
cinny/src/app/utils/user-agent.test.ts
T

68 lines
2.3 KiB
TypeScript
Raw Normal View History

import { test, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { isMacOS, mobileOrTablet } from './user-agent';
// `ua()` reads `window.navigator.userAgent` lazily on every call, so we can swap
// the global mock per test case and restore it afterwards.
const UA = {
mac: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36',
windows:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36',
linux:
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36',
iphone:
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
ipad: 'Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1',
android:
'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Mobile Safari/537.36',
};
const g = globalThis as unknown as { window?: unknown };
const originalWindow = g.window;
const setUserAgent = (userAgent: string) => {
g.window = { navigator: { userAgent } };
};
afterEach(() => {
g.window = originalWindow;
});
test('isMacOS returns true for a Mac user agent (handles both macOS and legacy Mac OS)', () => {
setUserAgent(UA.mac);
assert.equal(isMacOS(), true);
});
test('isMacOS returns false for non-Mac user agents', () => {
setUserAgent(UA.windows);
assert.equal(isMacOS(), false);
setUserAgent(UA.linux);
assert.equal(isMacOS(), false);
setUserAgent(UA.android);
assert.equal(isMacOS(), false);
});
test('mobileOrTablet is true for an iPhone', () => {
setUserAgent(UA.iphone);
assert.equal(mobileOrTablet(), true);
});
test('mobileOrTablet is true for an iPad', () => {
setUserAgent(UA.ipad);
assert.equal(mobileOrTablet(), true);
});
test('mobileOrTablet is true for an Android device', () => {
setUserAgent(UA.android);
assert.equal(mobileOrTablet(), true);
});
test('mobileOrTablet is false for desktop user agents', () => {
setUserAgent(UA.mac);
assert.equal(mobileOrTablet(), false);
setUserAgent(UA.windows);
assert.equal(mobileOrTablet(), false);
setUserAgent(UA.linux);
assert.equal(mobileOrTablet(), false);
});