graph-ecs/tests/query.test.js
2024-11-22 05:03:41 -06:00

74 lines
2.2 KiB
JavaScript

import { beforeEach, describe, it } from 'node:test'
import { addComponent, addEntity, createWorld, defineComponent, Types } from 'bitecs'
import assert from './assert.js'
import { query } from '../src/query.js'
let engine = {}
describe('query', () => {
beforeEach(() => {
const world = { default: createWorld() }
const component = {
Player: defineComponent(null, 10),
NPC: defineComponent(null, 10),
Knows: defineComponent({
from: Types.eid,
to: Types.eid
}, 10)
}
engine = { world, component }
})
it('i just need a test runner', () => {
const w = engine.world.default
const { Player, NPC, Knows } = engine.component
const create = (...components) => {
const eid = addEntity(w)
components.forEach(cmp => addComponent(w, cmp, eid))
return eid
}
const relate = (a, type, ...b) => {
return b.map(v => {
const edge = addEntity(w)
addComponent(w, type, edge)
type.from[edge] = a
type.to[edge] = v
return edge
})
}
const player = create(Player) // 0
const a = create(NPC) // 1
const b = create(NPC) // 2
const c = create(NPC) // 3
relate(player, Knows, a, c) // 4, 5
relate(a, Knows, player, b, c) // 6, 7, 8
relate(b, Knows, a) // 9
relate(c, Knows, player) // 10
assert.deepEqual(
query('MATCH (player:Player) RETURN player', engine).unwrap(),
[{ player: 0 }]
)
assert.deepEqual(
query('MATCH (player:Player)-[e1:Knows]->(a:NPC) RETURN player, e1, a', engine).unwrap(),
[
{ player: 0, e1: 4, a: 1 },
{ player: 0, e1: 5, a: 3 }
]
)
assert.deepEqual(
query('MATCH (player:Player)-[e1:Knows]->(a:NPC)-[e2:Knows]->(b:NPC) RETURN player, e1, a, e2, b', engine).unwrap(),
[
{ player: 0, e1: 4, a: 1, e2: 7, b: 2 },
{ player: 0, e1: 4, a: 1, e2: 8, b: 3 }
]
)
})
})