test: Adds tests for ast-utils - isRoot, assertRoot
ADD
internal/ast-utils/assertRoot.test.ts
+import {test} from "rome";
+import {parseJS} from "@internal/js-parser";
+import {parseCSS} from "@internal/css-parser";
+import {assertRoot} from "./assertRoot";
+
+test(
+ "root node should be returned",
+ async (t) => {
+ const jsNode = parseJS({
+ path: "unknown",
+ input: "function test() { return true; }",
+ });
+
+ t.is(assertRoot(jsNode), jsNode);
+
+ const cssNode = parseCSS({
+ path: "unknown",
+ input: "div { color: red; }",
+ });
+
+ t.is(assertRoot(cssNode), cssNode);
+ },
+);
+
+test(
+ "non-root node should throw error",
+ async (t) => {
+ const jsNode = parseJS({
+ path: "unknown",
+ input: "function test() { return true; }",
+ });
+
+ t.throws(() => {
+ assertRoot(jsNode.body[0]);
+ });
+ },
+);

MODIFY
internal/ast-utils/assertRoot.ts
internal/ast-utils/assertRoot.ts
import {AnyNode, AnyRoot} from "@internal/ast";
import {isRoot} from "./isRoot";
-export function assertRoot(node: AnyNode): AnyRoot {
+export function assertRoot(node: AnyNode): AnyRoot | never {
if (isRoot(node)) {
return node;
- } else {
- throw new Error(`Expected root node but got ${node.type}`);
}
+ throw new Error(`Expected root node but got ${node.type}`);
}

ADD
internal/ast-utils/isRoot.test.ts
+import {test} from "rome";
+import {AnyNode} from "@internal/ast";
+import {isRoot} from "./isRoot";
+
+function createNode(type: string): AnyNode {
+ return ({
+ type,
+ } as AnyNode);
+}
+
+test(
+ "valid roots return true",
+ async (t) => {
+ function createNode(type: string) {
+ return ({
+ type,
+ } as AnyNode);
+ }
+
+ const validRoots = [
+ "JSRoot",
+ "CSSRoot",
+ "CommitRoot",
+ "MarkdownRoot",
+ "HTMLRoot",
+ ];
+
+ validRoots.forEach((r) => {
+ t.is(isRoot(createNode(r)), true);
+ });
+ },
+);
+
+test(
+ "invalid roots return false",
+ async (t) => {
+ const invalidRoots = [
+ "CommentBlock",
+ "CommentLine",
+ "JSUpdateExpression",
+ "TSTypeQuery",
+ "TSUnionTypeAnnotation",
+ ];
+
+ invalidRoots.forEach((r) => {
+ t.is(isRoot(createNode(r)), false);
+ });
+ },
+);

MODIFY
internal/ast-utils/isRoot.ts
internal/ast-utils/isRoot.ts
import {AnyNode, AnyRoot} from "@internal/ast";
+const roots = new Set([
+ "JSRoot",
+ "CSSRoot",
+ "CommitRoot",
+ "MarkdownRoot",
+ "HTMLRoot",
+]);
+
export function isRoot(node: AnyNode): node is AnyRoot {
- return (
- node.type === "JSRoot" ||
- node.type === "CSSRoot" ||
- node.type === "CommitRoot" ||
- node.type === "MarkdownRoot" ||
- node.type === "HTMLRoot"
- );
+ return roots.has(node.type);
}

test: Adds tests for ast-utils - isRoot, assertRoot (#1227)