'Is there a way to easily compare 2 AST structures disregarding position?

Is there a way to easily compare 2 ast's on babel?

Consider a program like this as the source file:

// example.ts
import { foo } from "bar";

describe("Some test", () => {
  let moduleFixture: any;
  beforeAll(async () => {
    moduleFixture = await foo.createTestingModule({}).compile();
  });

  afterAll(async () => {
    await foo.tearDown();
  });
});

And consider the following babel program

const babelParser = require("@babel/parser");
const { default: traverse } = require("@babel/traverse");
const { readFileSync } = require("fs");
const recast = require("recast");
const { default: template } = require("@babel/template");

const source = readFileSync(`./example.ts`, "utf-8");

const buildBeforeAll = template(
  `  beforeAll(async () => {
    moduleFixture = await foo.createTestingModule({}).compile();
  });  `,
  {
    plugins: ["typescript"],
  }
);

const beforeAllAst = buildBeforeAll();
const ast = babelParser.parse(source, {
  allowImportExportEverywhere: true,
  plugins: ["typescript"],
});

traverse(ast, {
  enter(path) {
    const isBeforeAll = path.isIdentifier({ name: "beforeAll" });
    if (isBeforeAll) {
      // Somehow compare is beforeAllASt === path
      console.log(`found an appropriate beforeall`);
      path.replaceWithSourceString(`beforeEach`);
    }
  },
});
console.log(recast.print(ast).code);

What would be the best way to compare beforeAllAst with a traversed node?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source