silphius/app/astride/evaluators/call.test.js
2024-06-30 14:29:10 -05:00

63 lines
1.9 KiB
JavaScript

import {expect, test} from 'vitest';
import evaluate from '@/astride/evaluate.js';
import expression from '@/astride/test/expression.js';
const scopeTest = test.extend({
scope: async ({}, use) => {
await use({
S: {O: {}},
get(k) { return this.S[k]; },
set(k, v) { return this.S[k] = v; }
});
},
});
scopeTest('evaluates calls', async ({scope}) => {
scope.set('f', (...args) => args.reduce((l, r) => l + r, 0));
const evaluated = evaluate(await expression('f(1, 2, 3)'), {scope});
expect(evaluated.value)
.to.equal(6);
});
scopeTest('evaluates async calls', async ({scope}) => {
const f = (...args) => args.reduce((l, r) => l + r, 0);
scope.set('f', f);
scope.set('O', {f});
const evaluated = evaluate(await expression('f(await 1, 2, 3)'), {scope});
expect(evaluated.async)
.to.equal(true);
expect(await evaluated.value)
.to.equal(6);
const evaluatedOptional = evaluate(await expression('O?.f(await 1, 2, 3)'), {scope});
expect(evaluatedOptional.async)
.to.equal(true);
expect(await evaluatedOptional.value)
.to.equal(6);
});
scopeTest('evaluates member calls', async ({scope}) => {
scope.set('O', {f: (...args) => args.reduce((l, r) => l + r, 0)});
expect(evaluate(await expression('O.f(1, 2, 3)'), {scope}).value)
.to.equal(6);
expect(evaluate(await expression('O["f"](1, 2, 3)'), {scope}).value)
.to.equal(6);
});
scopeTest('evaluates optional calls', async ({scope}) => {
scope.set('O', {});
expect(evaluate(await expression('g?.(1, 2, 3)'), {scope}).value)
.to.equal(undefined);
expect(evaluate(await expression('O?.g?.(1, 2, 3)'), {scope}).value)
.to.equal(undefined);
});
scopeTest('evaluates async calls', async ({scope}) => {
scope.set('O', {f: (...args) => args.reduce((l, r) => l + r, 0)});
const evaluated = evaluate(await expression('O.f(await 1, 2, 3)'), {scope});
expect(evaluated.async)
.to.equal(true);
expect(await evaluated.value)
.to.equal(6);
});