identityVisitor.test.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { assertIsNode, numberTypeNode, publicKeyTypeNode, tupleTypeNode } from '@codama/nodes';
  2. import { expect, test } from 'vitest';
  3. import { identityVisitor, interceptVisitor, visit } from '../src';
  4. test('it visits all nodes and returns different instances of the same nodes', () => {
  5. // Given the following 3-nodes tree.
  6. const node = tupleTypeNode([numberTypeNode('u32'), publicKeyTypeNode()]);
  7. // When we visit it using the identity visitor.
  8. const result = visit(node, identityVisitor());
  9. // Then we get the same tree back.
  10. expect(result).toEqual(node);
  11. // But the nodes are different instances.
  12. expect(result).not.toBe(node);
  13. assertIsNode(result, 'tupleTypeNode');
  14. expect(result.items[0]).not.toBe(node.items[0]);
  15. expect(result.items[1]).not.toBe(node.items[1]);
  16. });
  17. test('it can remove nodes by returning null', () => {
  18. // Given the following 3-nodes tree.
  19. const node = tupleTypeNode([numberTypeNode('u32'), publicKeyTypeNode()]);
  20. // And given an identity visitor overidden to remove all public key nodes.
  21. const visitor = identityVisitor();
  22. visitor.visitPublicKeyType = () => null;
  23. // When we visit it using that visitor.
  24. const result = visit(node, visitor);
  25. // Then we expect the following tree back.
  26. expect(result).toEqual(tupleTypeNode([numberTypeNode('u32')]));
  27. });
  28. test('it can create partial visitors', () => {
  29. // Given the following 3-nodes tree.
  30. const node = tupleTypeNode([numberTypeNode('u32'), publicKeyTypeNode()]);
  31. // And an identity visitor that only supports 2 of these nodes
  32. // whilst using an interceptor to record the events that happened.
  33. const events: string[] = [];
  34. const visitor = interceptVisitor(identityVisitor({ keys: ['tupleTypeNode', 'numberTypeNode'] }), (node, next) => {
  35. events.push(`visiting:${node.kind}`);
  36. return next(node);
  37. });
  38. // When we visit the tree using that visitor.
  39. const result = visit(node, visitor);
  40. // Then we still get the full tree back as different instances.
  41. expect(result).toEqual(node);
  42. expect(result).not.toBe(node);
  43. assertIsNode(result, 'tupleTypeNode');
  44. expect(result.items[0]).not.toBe(node.items[0]);
  45. expect(result.items[1]).not.toBe(node.items[1]);
  46. // But the unsupported node was not visited.
  47. expect(events).toEqual(['visiting:tupleTypeNode', 'visiting:numberTypeNode']);
  48. // And the unsupported node cannot be visited.
  49. // @ts-expect-error PublicKeyTypeNode is not supported.
  50. expect(() => visit(publicKeyTypeNode(), visitor)).toThrow();
  51. });