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

68 lines
2.1 KiB
JavaScript

import { test, expect } from 'bun:test';
import { readFileSync } from 'fs';
import { join } from 'path';
import { DOMParser } from './setup.js';
import { NJSParser } from '../mod.js';
function loadFixture(filename) {
const path = join(process.cwd(), '..', 'test', 'src', filename);
return readFileSync(path, 'utf-8');
}
test('factory exposes core namespaces and functions', () => {
const parser = NJSParser({ DOMParser });
expect(parser).toBeTruthy();
expect(parser.parser).toBeTruthy();
expect(parser.types).toBeTruthy();
expect(parser.api).toBeTruthy();
expect(parser.utils).toBeTruthy();
expect(typeof parser.hasNextJS).toBe('function');
expect(typeof parser.findBuildId).toBe('function');
expect(typeof parser.BeautifulFD).toBe('function');
});
test('hasNextJS detects NextJS vs non-NextJS fixtures', () => {
const parser = NJSParser({ DOMParser });
const nextHtml = loadFixture('nextjs.org.html');
const nonNextHtml = loadFixture('x.com.html');
expect(parser.hasNextJS(nextHtml)).toBe(true);
expect(parser.hasNextJS(nonNextHtml)).toBe(false);
});
test('findBuildId finds build id on nextjs.org.html', () => {
const parser = NJSParser({ DOMParser });
const html = loadFixture('nextjs.org.html');
const buildId = parser.findBuildId(html);
expect(typeof buildId).toBe('string');
expect(buildId.length).toBeGreaterThan(0);
});
test('BeautifulFD constructed from HTML can iterate at least one element', () => {
const parser = NJSParser({ DOMParser });
const html = loadFixture('nextjs.org.html');
const fd = new parser.BeautifulFD(html);
const iter = fd.find_iter();
const first = iter.next();
expect(first.done).toBe(false);
expect(first.value).toBeTruthy();
});
test('BeautifulFD without DOMParser injected should throw when given HTML', () => {
expect(() => {
const parser = NJSParser({ DOMParser: undefined });
const html = loadFixture('nextjs.org.html');
// constructor will try to parse HTML => should fail due to missing DOMParser
// eslint-disable-next-line no-new
new parser.BeautifulFD(html);
}).toThrow();
});