mapVisitor.test.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { numberTypeNode, publicKeyTypeNode, tupleTypeNode } from '@codama/nodes';
  2. import { expect, test } from 'vitest';
  3. import { mapVisitor, mergeVisitor, staticVisitor, visit, Visitor } from '../src';
  4. test('it maps the return value of a visitor to another', () => {
  5. // Given the following 3-nodes tree.
  6. const node = tupleTypeNode([numberTypeNode('u32'), publicKeyTypeNode()]);
  7. // And a merge visitor A that lists the kind of each node.
  8. const visitorA = mergeVisitor(
  9. node => node.kind as string,
  10. (node, values) => `${node.kind}(${values.join(',')})`,
  11. );
  12. // And a mapped visitor B that returns the number of characters returned by visitor A.
  13. const visitorB = mapVisitor(visitorA, value => value.length);
  14. // Then we expect the following results when visiting different nodes.
  15. expect(visit(node, visitorB)).toBe(47);
  16. expect(visit(node.items[0], visitorB)).toBe(14);
  17. expect(visit(node.items[1], visitorB)).toBe(17);
  18. });
  19. test('it creates partial visitors from partial visitors', () => {
  20. // Given the following 3-nodes tree.
  21. const node = tupleTypeNode([numberTypeNode('u32'), publicKeyTypeNode()]);
  22. // And partial static visitor A that supports only 2 of these nodes.
  23. const visitorA = staticVisitor(node => node.kind, { keys: ['tupleTypeNode', 'numberTypeNode'] });
  24. // And a mapped visitor B that returns the number of characters returned by visitor A.
  25. const visitorB = mapVisitor(visitorA, value => value.length);
  26. // Then both visitors are partial.
  27. visitorA satisfies Visitor<string, 'numberTypeNode' | 'tupleTypeNode'>;
  28. visitorB satisfies Visitor<number, 'numberTypeNode' | 'tupleTypeNode'>;
  29. // Then we expect an error when visiting an unsupported node.
  30. // @ts-expect-error PublicKeyTypeNode is not supported.
  31. expect(() => visit(node.items[1], visitorB)).toThrow();
  32. });