| 1 | import _checkDuplicateNodes from "../lib/index.js"; |
| 2 | import { parseSync, traverse, types as t } from "@babel/core"; |
| 3 | const checkDuplicateNodes = |
| 4 | _checkDuplicateNodes.default || _checkDuplicateNodes; |
| 5 | |
| 6 | describe("checkDuplicateNodes", () => { |
| 7 | it("should throw on duplicate AST nodes within same parent", () => { |
| 8 | const ast = parseSync("{}", { |
| 9 | filename: "example.js", |
| 10 | configFile: false, |
| 11 | }); |
| 12 | traverse(ast, { |
| 13 | BlockStatement(path) { |
| 14 | const { node } = path; |
| 15 | const duplicate = t.identifier("ref"); |
| 16 | const statementBody = node.body; |
| 17 | statementBody.unshift( |
| 18 | t.variableDeclaration("var", [ |
| 19 | t.variableDeclarator(duplicate, duplicate), |
| 20 | ]), |
| 21 | ); |
| 22 | path.stop(); |
| 23 | }, |
| 24 | }); |
| 25 | expect(() => { |
| 26 | checkDuplicateNodes(ast); |
| 27 | }).toThrowErrorMatchingSnapshot(); |
| 28 | }); |
| 29 | it("should throw on duplicate AST nodes within different parent", () => { |
| 30 | const ast = parseSync("{}", { |
| 31 | filename: "example.js", |
| 32 | configFile: false, |
| 33 | }); |
| 34 | traverse(ast, { |
| 35 | BlockStatement(path) { |
| 36 | const { node } = path; |
| 37 | const duplicate = t.identifier("ref"); |
| 38 | const statementBody = node.body; |
| 39 | statementBody.unshift( |
| 40 | t.variableDeclaration("var", [t.variableDeclarator(duplicate)]), |
| 41 | ); |
| 42 | statementBody.unshift( |
| 43 | t.expressionStatement( |
| 44 | t.assignmentExpression("=", duplicate, t.nullLiteral()), |
| 45 | ), |
| 46 | ); |
| 47 | path.stop(); |
| 48 | }, |
| 49 | }); |
| 50 | expect(() => { |
| 51 | checkDuplicateNodes(ast); |
| 52 | }).toThrowErrorMatchingSnapshot(); |
| 53 | }); |
| 54 | it("should throw when more than one arguments are passed", () => { |
| 55 | expect(() => { |
| 56 | checkDuplicateNodes({}, {}); |
| 57 | }).toThrow("checkDuplicateNodes accepts only one argument: ast"); |
| 58 | }); |
| 59 | }); |