diff --git a/src/language/__tests__/visitor-test.js b/src/language/__tests__/visitor-test.js index 353fc13951..eed3270fa1 100644 --- a/src/language/__tests__/visitor-test.js +++ b/src/language/__tests__/visitor-test.js @@ -74,7 +74,6 @@ describe('Visitor', () => { checkVisitorFnArgs(ast, arguments); visited.push(['enter', path.slice()]); }, - leave(node, key, parent, path) { checkVisitorFnArgs(ast, arguments); visited.push(['leave', path.slice()]); @@ -95,6 +94,34 @@ describe('Visitor', () => { ]); }); + it('validates ancestors argument', () => { + const ast = parse('{ a }', { noLocation: true }); + const visitedNodes = []; + + visit(ast, { + enter(node, key, parent, path, ancestors) { + const inArray = typeof key === 'number'; + if (inArray) { + visitedNodes.push(parent); + } + visitedNodes.push(node); + + const expectedAncestors = visitedNodes.slice(0, -2); + expect(ancestors).to.deep.equal(expectedAncestors); + }, + leave(node, key, parent, path, ancestors) { + const expectedAncestors = visitedNodes.slice(0, -2); + expect(ancestors).to.deep.equal(expectedAncestors); + + const inArray = typeof key === 'number'; + if (inArray) { + visitedNodes.pop(); + } + visitedNodes.pop(); + }, + }); + }); + it('allows editing a node both on enter and on leave', () => { const ast = parse('{ a, b, c { a, b, c } }', { noLocation: true }); diff --git a/src/language/visitor.js b/src/language/visitor.js index 00e4510992..32c1af78ba 100644 --- a/src/language/visitor.js +++ b/src/language/visitor.js @@ -40,9 +40,9 @@ export type VisitFn = ( parent: TAnyNode | $ReadOnlyArray | void, // The key path to get to this node from the root node. path: $ReadOnlyArray, - // All nodes and Arrays visited before reaching this node. + // All nodes and Arrays visited before reaching parent of this node. // These correspond to array indices in `path`. - // Note: ancestors includes arrays which contain the visited node. + // Note: ancestors includes arrays which contain the parent of visited node. ancestors: $ReadOnlyArray>, ) => any;