avocado/packages/entity/test/json.js
2024-01-28 11:51:17 -06:00

82 lines
2.5 KiB
JavaScript

/* eslint-disable global-require */
import {Flecks} from '@flecks/core';
import {expect} from 'chai';
let flecks;
let Entity;
beforeEach(async () => {
flecks = await Flecks.from({
flecks: {
'@avocado/behavior': require('@avocado/behavior'),
'@avocado/entity': require('@avocado/entity'),
'@avocado/graphics': require('@avocado/graphics'),
'@avocado/resource': require('@avocado/resource'),
'@avocado/traits': require('@avocado/traits'),
'@flecks/core': require('@flecks/core'),
'@flecks/react': require('@flecks/react'),
},
});
({Entity} = flecks.avocado.resource.Resources);
});
afterEach(() => {
flecks.destroy();
});
it('outputs JSON', () => {
const entity = new Entity();
expect(entity.toJSON()).to.deep.equal({});
entity.uri = '/foo/bar';
expect(entity.toJSON()).to.deep.equal({extends: entity.uri});
});
it('can trim defaults from JSON', async () => {
const entity = new Entity();
await entity.addTrait('Alive');
expect(Entity.withoutDefaults(entity.toJSON()))
.to.deep.equal({traits: {Alive: {}}});
entity.life = 40;
expect(Entity.withoutDefaults(entity.toJSON()))
.to.deep.equal({traits: {Alive: {state: {life: 40}}}});
entity.maxLife = 420;
expect(Entity.withoutDefaults(entity.toJSON()))
.to.deep.equal({traits: {Alive: {state: {life: 40, maxLife: 420}}}});
entity.maxLife = 100;
expect(Entity.withoutDefaults(entity.toJSON()))
.to.deep.equal({traits: {Alive: {state: {life: 40}}}});
});
it('can add defaults to JSON', async () => {
expect(Entity.withDefaults({traits: {Directional: {}}}))
.to.deep.equal({
traits: {
Directional: {params: {directionCount: 1, trackMovement: true}, state: {direction: 0}},
},
});
});
it('can output JSON optimized for network', async () => {
const entity = new Entity();
entity.uri = '/foo/bar';
await entity.addTrait('Directional', {directionCount: 4});
entity.direction = 1;
expect(entity.toNetwork())
.to.deep.equal({
extends: '/foo/bar',
instanceUuid: entity.instanceUuid,
traits: {Directional: {state: {direction: 1}}},
});
});
it('can fallback to sending whole info when there is no base', async () => {
const entity = new Entity();
await entity.addTrait('Directional', {directionCount: 4});
entity.direction = 1;
expect(entity.toNetwork())
.to.deep.equal({
instanceUuid: entity.instanceUuid,
traits: {
Directional: {params: {directionCount: 1, trackMovement: true}, state: {direction: 1}},
},
});
});