refs.spec.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { rehypePlugin } from './refs';
  2. type RefTagName = 'ref' | 'refimg' | 'refs' | 'refsimg' | 'gallery';
  3. const createTree = (
  4. tagName: RefTagName,
  5. properties: Record<string, unknown> = {},
  6. ) => ({
  7. type: 'root',
  8. children: [
  9. {
  10. type: 'element',
  11. tagName,
  12. properties,
  13. children: [],
  14. },
  15. ],
  16. });
  17. const runRehype = (
  18. tree: ReturnType<typeof createTree>,
  19. options: { pagePath?: string; isSharedPage?: boolean },
  20. ): void => {
  21. // WHY: unified's `Plugin` type is not directly callable; narrow it to the
  22. // (options) => (tree) => void shape this factory plugin actually has.
  23. (rehypePlugin as (opts: typeof options) => (tree: unknown) => void)(options)(
  24. tree,
  25. );
  26. };
  27. const getProperties = (
  28. tree: ReturnType<typeof createTree>,
  29. ): Record<string, unknown> =>
  30. (tree.children[0] as { properties: Record<string, unknown> }).properties;
  31. const tags: RefTagName[] = ['ref', 'refimg', 'refs', 'refsimg', 'gallery'];
  32. describe('refs rehypePlugin - isSharedPage injection', () => {
  33. it.each(
  34. tags,
  35. )('injects isSharedPage=true into <%s> when the option is set', (tagName) => {
  36. const tree = createTree(tagName);
  37. runRehype(tree, { pagePath: '/foo', isSharedPage: true });
  38. expect(getProperties(tree).isSharedPage).toBe(true);
  39. });
  40. it.each(
  41. tags,
  42. )('leaves isSharedPage undefined on <%s> when the option is omitted', (tagName) => {
  43. const tree = createTree(tagName);
  44. runRehype(tree, { pagePath: '/foo' });
  45. expect(getProperties(tree).isSharedPage).toBeUndefined();
  46. });
  47. it('does not override an isSharedPage already present on the element', () => {
  48. const tree = createTree('refs', { isSharedPage: false });
  49. runRehype(tree, { pagePath: '/foo', isSharedPage: true });
  50. expect(getProperties(tree).isSharedPage).toBe(false);
  51. });
  52. });