njsparser/js/tests/parser/urls.test.js
2026-02-15 01:34:37 +01:00

84 lines
2.6 KiB
JavaScript

import { test, expect } from 'bun:test';
import { readFileSync } from 'fs';
import { join } from 'path';
import { DOMParser } from '../setup.js';
import { getNextStaticUrls, getBasePath, _NS } from '../../parser/urls.js';
function loadTestHTML(filename) {
const path = join(process.cwd(), '..', 'test', 'src', filename);
return readFileSync(path, 'utf-8');
}
test('getNextStaticUrls finds URLs in nextjs.org.html', () => {
const html = loadTestHTML('nextjs.org.html');
const urls = getNextStaticUrls(html, DOMParser);
expect(urls).not.toBeNull();
expect(Array.isArray(urls)).toBe(true);
expect(urls.length).toBeGreaterThan(0);
expect(urls.every(url => url.includes(_NS))).toBe(true);
});
test('getNextStaticUrls returns null for no static URLs', () => {
const html = '<html><body>No static URLs</body></html>';
const urls = getNextStaticUrls(html, DOMParser);
expect(urls).toBeNull();
});
test('getNextStaticUrls finds URLs in swag.live.html', () => {
const html = loadTestHTML('swag.live.html');
const urls = getNextStaticUrls(html, DOMParser);
expect(urls).not.toBeNull();
expect(Array.isArray(urls)).toBe(true);
});
test('getBasePath extracts base path from URLs', () => {
const urls = [
'/_next/static/abc/chunk1.js',
'/_next/static/abc/chunk2.js'
];
const basePath = getBasePath(urls);
expect(basePath).toBe('');
});
test('getBasePath extracts base path with prefix', () => {
const urls = [
'/app/_next/static/abc/chunk1.js',
'/app/_next/static/abc/chunk2.js'
];
const basePath = getBasePath(urls);
expect(basePath).toBe('/app');
});
test('getBasePath throws on inconsistent prefixes', () => {
const urls = [
'/app1/_next/static/abc/chunk1.js',
'/app2/_next/static/abc/chunk2.js'
];
expect(() => getBasePath(urls)).toThrow();
});
test('getBasePath throws on missing _NS', () => {
const urls = ['/invalid/path.js'];
expect(() => getBasePath(urls)).toThrow("can't find");
});
test('getBasePath removes domain when requested', () => {
const urls = [
'https://example.com/app/_next/static/abc/chunk1.js',
'https://example.com/app/_next/static/abc/chunk2.js'
];
const basePath = getBasePath(urls, null, true);
expect(basePath).toBe('/app');
});
test('getBasePath from HTML', () => {
const html = loadTestHTML('nextjs.org.html');
const basePath = getBasePath(html, DOMParser);
expect(typeof basePath).toBe('string');
});
test('getBasePath returns null for HTML with no static URLs', () => {
const html = '<html><body>No static URLs</body></html>';
const basePath = getBasePath(html, DOMParser);
expect(basePath).toBeNull();
});