Skip to content

Commit

Permalink
add a test for maybeParseAsExpression
Browse files Browse the repository at this point in the history
  • Loading branch information
danvk committed Jan 19, 2024
1 parent 80d5998 commit 97aabdc
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
53 changes: 52 additions & 1 deletion src/main.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as fs from "node:fs/promises";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { main, resetErrors } from "./main.js";
import { main, maybeParseAsExpression, resetErrors } from "./main.js";
import { mockError, mockExit, mockLog } from "./test-utils.js";

vi.mock("node:fs/promises");
Expand Down Expand Up @@ -61,4 +61,55 @@ describe("main", () => {
"Operands must be two numbers or two strings.\n[line 1]",
);
});

describe("maybeParseAsExpression", () => {
it("should parse an expressions", () => {
const error = mockError();
expect(maybeParseAsExpression("1 + 2*2")).toMatchInlineSnapshot(`
{
"kind": "binary",
"left": {
"kind": "literal",
"value": 1,
},
"operator": {
"lexeme": "+",
"line": 1,
"literal": null,
"type": "+",
},
"right": {
"kind": "binary",
"left": {
"kind": "literal",
"value": 2,
},
"operator": {
"lexeme": "*",
"line": 1,
"literal": null,
"type": "*",
},
"right": {
"kind": "literal",
"value": 2,
},
},
}
`);
expect(error).not.toHaveBeenCalled();
});

it("should return null and not log on a statement", () => {
const error = mockError();
expect(maybeParseAsExpression("1 + 2*2;")).toBeNull();
expect(error).not.toHaveBeenCalled();
});

it("should return null and not log on a syntax error", () => {
const error = mockError();
expect(maybeParseAsExpression("1 + 2*")).toBeNull();
expect(error).not.toHaveBeenCalled();
});
});
});
2 changes: 1 addition & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ let throwMode = false;

class ParseError extends Error {}

function maybeParseAsExpression(line: string): Expr | null {
export function maybeParseAsExpression(line: string): Expr | null {
throwMode = true;
try {
const scanner = new Scanner(line + ";");
Expand Down

0 comments on commit 97aabdc

Please sign in to comment.