Skip to content

Commit

Permalink
Set correct path.context un push/unshiftContainer (#12394)
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Nov 25, 2020
1 parent 0f3db5d commit 695abb8
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
2 changes: 2 additions & 0 deletions packages/babel-traverse/src/context.js
Expand Up @@ -42,6 +42,8 @@ export default class TraversalContext {
}

create(node, obj, key, listKey): NodePath {
// We don't need to `.setContext()` here, since `.visitQueue()` already
// calls `.pushContext`.
return NodePath.get({
parentPath: this.parentPath,
parent: node,
Expand Down
4 changes: 2 additions & 2 deletions packages/babel-traverse/src/path/modification.js
Expand Up @@ -217,7 +217,7 @@ export function unshiftContainer(listKey, nodes) {
container: this.node[listKey],
listKey,
key: 0,
});
}).setContext(this.context);

return path._containerInsertBefore(nodes);
}
Expand All @@ -237,7 +237,7 @@ export function pushContainer(listKey, nodes) {
container: container,
listKey,
key: container.length,
});
}).setContext(this.context);

return path.replaceWithMultiple(nodes);
}
Expand Down
40 changes: 40 additions & 0 deletions packages/babel-traverse/test/modification.js
Expand Up @@ -49,6 +49,26 @@ describe("modification", function () {
},
});
});

it("should set the correct path.context", function () {
expect.assertions(2);

const ast = parse("[b];");
traverse(ast, {
skipKeys: ["consequent"],
ExpressionStatement(path) {
path.traverse({ Identifier() {}, skipKeys: [] });

const arr = path.get("expression");
const x = arr.pushContainer("elements", [
{ type: "Identifier", name: "x" },
])[0];

expect(x.node.name).toBe("x");
expect(x.opts.skipKeys).toEqual(["consequent"]);
},
});
});
});
describe("unshiftContainer", function () {
it("unshifts identifier into params", function () {
Expand Down Expand Up @@ -78,6 +98,26 @@ describe("modification", function () {
},
});
});

it("should set the correct path.context", function () {
expect.assertions(2);

const ast = parse("[b];");
traverse(ast, {
skipKeys: ["consequent"],
ExpressionStatement(path) {
path.traverse({ Identifier() {}, skipKeys: [] });

const arr = path.get("expression");
const x = arr.unshiftContainer("elements", [
{ type: "Identifier", name: "x" },
])[0];

expect(x.node.name).toBe("x");
expect(x.opts.skipKeys).toEqual(["consequent"]);
},
});
});
});

describe("insertBefore", function () {
Expand Down

0 comments on commit 695abb8

Please sign in to comment.