interceptVisitor.test.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { numberTypeNode, publicKeyTypeNode, tupleTypeNode } from '@kinobi-so/nodes';
  2. import test from 'ava';
  3. import { interceptVisitor, visit, voidVisitor } from '../src/index.js';
  4. test('it returns a new visitor that intercepts all visits of a visitor', t => {
  5. // Given the following 3-nodes tree.
  6. const node = tupleTypeNode([numberTypeNode('u32'), publicKeyTypeNode()]);
  7. // And an intercepted void visitor that records the events that happened during each visit.
  8. const events: string[] = [];
  9. const baseVisitor = voidVisitor();
  10. const visitor = interceptVisitor(baseVisitor, (node, next) => {
  11. events.push(`down:${node.kind}`);
  12. next(node);
  13. events.push(`up:${node.kind}`);
  14. });
  15. // When we visit the tree using that visitor.
  16. visit(node, visitor);
  17. // Then we expect the following events to have happened.
  18. t.deepEqual(events, [
  19. 'down:tupleTypeNode',
  20. 'down:numberTypeNode',
  21. 'up:numberTypeNode',
  22. 'down:publicKeyTypeNode',
  23. 'up:publicKeyTypeNode',
  24. 'up:tupleTypeNode',
  25. ]);
  26. // And the intercepted visitor is a new instance.
  27. t.not(baseVisitor, visitor);
  28. });