Writing tests in JavaScript¶
Audience: model authors and language authors · about 5 minutes · Prerequisites: Writing and running tests
Tests written in JavaScript¶
A test can also be a small JavaScript program that calls the workbench API: it can edit a copy of your model, run the checks, the program and the generator, and expect what comes back. Use it when a test needs more than the assertion kinds above, for example "after this edit the model still has no problems".
The tests live in a root of their own in the model, in the language JS Tests (jstest), next to the code they test. The
code can be in any language: a model's roots may each have their own language (Models, roots and imports).
The root is stored as plain JavaScript (calculator.tests.model.js), and you edit it in the projectional editor like any other root.
describe("Calculator model", () => {
it("has no problems", async () => {
expect(workbench.checks.run()).toHaveNoChecks();
});
it("prints the answer", async () => {
expect(await workbench.run.run()).toPrint("42");
});
it("adds a statement in one undoable step", async () => {
const stmt = workbench.model.of(workbench.surface.parse("bonus = result + 1\n")).roots()[0].children(workbench.model/concept.fileRoot/stmts)[0];
workbench.transaction(() => workbench.model.root().append(workbench.model/concept.fileRoot/stmts, stmt));
expect(workbench.model.root().children(workbench.model/concept.fileRoot/stmts)).toHaveLength(4);
});
});
The JS tests sample (File > Load Sample…) is a runnable version of this.
What a test sees. workbench is the workbench API, working on the model's other roots (the code under test). Each it gets its own
copy, so a test can edit freely and the next one starts from the original. it("name", { shared: true }, fn) runs on one copy that all
shared tests use and that is restored after each of them (faster when the setup is expensive). beforeEach and afterEach run around
every test of their suite, outer to inner; afterEach also runs after a failure. it("name", { timeout: 5000 }, fn) sets the time
limit (60 seconds otherwise). Top-level statements and the body of a describe run once, to collect the tests. A concept or slot is written as a reference, and Ctrl+Space after workbench.model/concept. lists the concepts of the code's language: workbench.model.active().nodes(workbench.model/concept.invoiceLine) and node.property(workbench.model/concept.invoiceLine/price). It is saved exactly like that (JavaScript would read it as a division), checked against the same language, and the runner runs it as workbench.model.resolve("concept", "invoiceLine"); workbench.model.resolve(...) is the one call that turns a name you have as text into a reference; a name written as text, such as nodes("comment"), is refused.
The editor. workbench.editor works in a test too: the first time a test touches it, a private editor is opened on that test's copy of the code (never on your open tab, and your cursor stays where it is), and from then on workbench.model, workbench.transaction and undo go through it, so workbench.editor.addChild, setConcept, wrap, undo and redo behave as they do for you, with the editor's own rules and undo history. You can also drive it the way a person does: await workbench.editor.select(nodeId) puts the caret on a cell (select(callId, 0) for a value a call holds itself, such as the 21 in double(21); an unfilled __Empty__ node selects the empty cell), await workbench.editor.key("Enter") or key("z", { ctrl: true }) presses a key, await workbench.editor.type("42", { replace: true }) types into the cell (and commits it), and await workbench.editor.complete("whi") opens completion, returns the names it offers and await workbench.editor.choose("while") picks one. The keys go to the editor's own key handler, not through the page, so they never reach the IDE's shortcuts. They are synthetic: a behaviour that depends on a trusted browser event still needs a check in the real editor. On the command line the private editor needs the editor's renderer, which only the IDE and the test runner have, so key tests are for the IDE and npm test.
Values and hand-built nodes. workbench.run.format(value) prints a run value the way the language's own grammar writes it (a KernelF list as list(1, 2)), so a test compares a result with text instead of carrying its own printer. workbench.model.node(head, ...children) builds a node by head (a real concept instance, not a bare object) to print, wrap with workbench.model.of or put into a tree. A test has no file system, debugger or shell.
expect. The usual matchers (toBe, toEqual, toBeTruthy, toContain, toHaveLength, toBeGreaterThan, toMatch,
toMatchObject, toThrow, toBeInstanceOf, ... with .not, .resolves and .rejects) and some for the workbench's results:
toHaveNoChecks() and toHaveCheck(text) (for workbench.checks.run()), toGenerate(text) (for workbench.generator.text()),
toRunTo(value) and toPrint(...lines) (for workbench.run.run()), toHaveKind(head) (for a node). Snapshots, mocks and fake
timers are not available.
Run just one. On a describe or an it, Alt+Enter (or the lightbulb) offers Run just this suite or test, which runs only that part against the open model and shows the verdict in the status line (asking first only if the project was never trusted).
A failing test shows the matcher's message with both sides of a comparison, and clicking it in the Tests pane jumps to the
expect(...) call (or the statement that threw).
Trust. A JS test root is JavaScript that can call the whole workbench API, so it can edit your models and files. It follows
the project's trust decision (Security and privacy): you are
asked once, when you open the project, and the tests of a trusted project run without asking, also after you change them (a
project with no folder on disk asks once per test file). Verify never asks: it runs the tests of a trusted project and
reports the others as not run (in restricted mode too). On the command line strukts test runs the tests of a bundled sample, and
those of any other folder only with --trust-project-code. Nothing sandboxes the code.
Add one. Import JS Tests into the model (Language > Import), then Add root node in the Explorer and choose that language: the new root is a JavaScript file in which describe, it, beforeEach and afterEach are available from completion. Run > Execute > Pin Current Behaviour as Test adds a case that asserts what the model does now (no check issues, or the current ones, and the generated text) when the open root is a JS test root.
Good to know. Write const/let for your own variables (the code runs in strict mode). JS Tests imports the JavaScript language, so switch, loops with labels, a?.b, classes, generators, destructuring and the rest are real structure you can edit, and a function () {} callback stays a function (it is not rewritten to an arrow). Several declarators in one statement (const a = 1, b = 2;) are kept as one declaration each, { a, b } as { "a": a, "b": b }, and 0xff, 1e3 and 1_000 keep their value. Anything the language has no concept for is kept as its own source text in a raw cell, saved and run as written. (a || b).map(f) keeps its parentheses.