Testing with fake worlds
Most of a view is built on your computer without the webapp, an account, the network or a running world. A fake world is a world described in a plain object and run by the kit inside your page. It has a name, data that changes, members and roles and it answers what the person sends. You write it yourself and can make it slow, empty, crowded or failing to check your view in each of these cases before your view meets them in a real world.
A fake world in one object
connectToHost({ fake: { world } }) builds a world from a plain object and resolves with it in the same shape as a real world from the webapp. The fake world below has members, roles, changing data and answers that take a moment:
import { useWorld } from './useWorld.js';
// What changes when the person acts: a variable of the file, read by `data`.
let total = 0;
// A fake world with what a test needs: members, roles, data that changes, slow answers.
const quiz = {
name: 'Quiz night',
owner: 'acme',
profile: { description: 'Questions every Friday', place: 'Milan' },
now: { text: 'Round 1' },
members: [
{ name: 'Ada', role: 'player', data: { score: 3 } },
{ name: 'Max', role: 'host', isMaster: true },
],
roles: [{ name: 'player', description: 'Answers' }, { name: 'host', description: 'Asks' }],
myRole: 'player',
data: {
total: { every: 200, value: () => total }, // read again every 200 ms
clock: (time) => new Date(time).toLocaleTimeString(), // a new value every second
},
// Answers after half a second, like a real world that takes its time.
onMessage: async () => {
await new Promise((resolve) => setTimeout(resolve, 500));
total += 1;
return `Added. The total is ${total}.`;
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: quiz } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
const last = world.messages.filter((message) => !message.fromMe).at(-1);
return (
<>
<p>{world.name}, {world.now?.text}. You are: {world.myRole}. Total: {world.data.total}. Time: {world.data.clock}</p>
<ul>
{world.members.map((member) => (
<li key={member.id}>{member.name} ({member.role}{member.isMaster ? ', master' : ''})</li>
))}
</ul>
<button onClick={() => world.send('add')}>Add one</button>
<p>{last ? last.text : 'No answer yet.'}</p>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// What changes when the person acts: a variable of the file, read by `data`.
let total = 0;
// A fake world with what a test needs: members, roles, data that changes, slow answers.
const quiz = {
name: 'Quiz night',
owner: 'acme',
profile: { description: 'Questions every Friday', place: 'Milan' },
now: { text: 'Round 1' },
members: [
{ name: 'Ada', role: 'player', data: { score: 3 } },
{ name: 'Max', role: 'host', isMaster: true },
],
roles: [{ name: 'player', description: 'Answers' }, { name: 'host', description: 'Asks' }],
myRole: 'player',
data: {
total: { every: 200, value: () => total }, // read again every 200 ms
clock: (time) => new Date(time).toLocaleTimeString(), // a new value every second
},
// Answers after half a second, like a real world that takes its time.
onMessage: async () => {
await new Promise((resolve) => setTimeout(resolve, 500));
total += 1;
return `Added. The total is ${total}.`;
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: quiz } });
const info = document.createElement('p');
const members = document.createElement('ul');
const button = document.createElement('button');
button.textContent = 'Add one';
button.onclick = () => world.send('add');
const answer = document.createElement('p');
document.body.append(info, members, button, answer);
world.subscribe((node) => {
info.textContent = `${node.name}, ${node.now?.text}. You are: ${node.myRole}. Total: ${node.data.total}. Time: ${node.data.clock}`;
members.replaceChildren(...node.members.map((member) => {
const item = document.createElement('li');
item.textContent = `${member.name} (${member.role}${member.isMaster ? ', master' : ''})`;
return item;
}));
const last = node.messages.filter((message) => !message.fromMe).at(-1);
answer.textContent = last ? last.text : 'No answer yet.';
});Because subscribe, send, members and data behave in the same way, the code of your view cannot tell a fake world from a real one. Switching to the real webapp takes only the removal of fake (below).
Every field
The type FakeNode describes a fake agent. The type FakeWorld describes a fake world and adds members and roles to the fields of FakeNode. Only name is required.
| Field | What it is | In your view |
|---|---|---|
name | The name of the world. Required. | world.name |
owner | The owner of the world ('demo' when left out). | world.profile.owner and world.address (owner/name) |
profile | { description, place, isVerified } with every field optional. | world.profile |
data | What the world shows by name (Data that changes). | world.data |
now | { text, next, actions }: the current state of the rules. Fixed for the whole life of the fake world. | world.now |
onMessage | (message, world, person) => answer: answers what the person sends. | new messages in world.messages |
onAction | (name, args, person) => answer: answers when the person chooses one of now.actions. | new messages in world.messages |
failNext | true: the next message the person sends fails. | a message with status: 'failed' |
members | The members of the world, each described like a fake agent with role and isMaster. | world.members |
roles | [{ name, description }]: the roles of the world. | world.roles |
me | The person who looks at your view: { nickname, ... } with any of name, surname, title, organization, city and country. The nickname is 'you' when left out. | world.me |
myRole | The role of the person. | world.myRole |
showsSenders | false: the world asks not to show who wrote each message. | world.showsSenders |
Your view receives these fields in the following form:
now.actions: each listed action ({ name, text, to }) becomes{ name, text, to, args: {}, canChoose: true, isRequested: false }and itstois added tonow.next.members: each member has anid,type: 'agent',status: 'online', itsrole,isMaster(falseunless you givetrue) and its owndatathat can change like the data of the world.canSendbecomestrueonce the world is online and staystrue. To test a moment when it is not the turn of the person, keep the turn indataand render the view from it.mekeeps only the fields the webapp could give (Who the person is) andidentity()resolves with it at once.
Data that changes
Each value of data is a constant, a function of time that the kit calls every second or an object { every, value } whose value the kit calls every every milliseconds (Data in a fake world has a running example). Your view receives the value of a function only when it changes. Your listener is not called while a function keeps returning the same value.
To make the world change when the person acts, keep the state in a module-level variable, change it in onMessage or onAction and read it in a data function. The example does this with total:
let total = 0;
const quiz = {
name: 'Quiz night',
data: { total: { every: 200, value: () => total } }, // read again every 200 ms
onMessage: () => {
total += 1;
return `Added. The total is ${total}.`;
},
};With a short every (100 to 200 ms) the change appears at once. While the value stays the same your view receives nothing.
Pitfall
A plain value is read once. The kit reads the board in data: { board } when the world starts and never sees a later change to the array (board[0][0] = 1). Read it through a function (board: { every: 200, value: () => board }) and give the function a new array on every change (board = board.map(...)) for your view to receive the change.
Pitfall
A list with one item arrives as the item itself (['Ada'] gives 'Ada') as in the data of a real world (The data of the world). A list that can have a single item keeps its shape inside an object (players: { list: ['Ada'] } stays { list: ['Ada'] }).
Answers: messages, questions, actions
onMessage(message, world, person) runs for every message the person sends and receives three arguments:
messagewithtext,image,files(the file the person sent with its name),from,timeandvalueswhen it answers a questionworldandpersonas{ name, address }(for the person'You'and'you/You').
The return value is the answer of the world:
| Return | The view gets |
|---|---|
'Hi' | a message with that text |
{ text, form: { fields: [...] } } | a question (a message with form that the person answers with message.answer(values)) |
{ text, media: [...], charts: [...] } | a message with videos, sounds, PDFs or links ({ url, type, title }, https: only) and charts ({ kind, series, alt }) |
{ text, images: [...], files: [...] } | a message with pictures and files ({ name, type, url } with a data URI in url) when an agent or a member answers |
{ from: 'Ada', text } | the answer as a message of Ada (one of the members of a fake world) |
nothing (undefined, null) | no answer |
| a promise of any of these | the answer when it resolves |
The answers of the world itself arrive as notes of its rules with isSystem: true, the name of the world in from and its id in fromId. Like the notes of a real world they keep text, media, charts and forms and drop pictures and files. To answer with a picture or a file, give the answer to a member with from or put the picture in the data of the world.
const arena = {
name: 'Arena',
members: [{ name: 'Ada', role: 'player' }],
onMessage: (message) => {
// The person's file, with its name.
if (message.files.length > 0) return `Got ${message.files[0].name}`;
// Ada says it: her message, picture included, with her id in fromId.
return { from: 'Ada', text: 'Look at my move', images: [boardPicture()] };
},
};Two cases arrive as they would from a real world: (1) a file in an answer has no name (name: null) because only the files the person sends keep their name and (2) a video whose address is not https: arrives as its description (alt) in text with nothing in media. Fake worlds › FakeAnswer lists every field of an answer.
An answered question arrives in onMessage as a message with values:
onMessage: (message) => {
if (message.values) return `You chose ${message.values.side}.`;
return { text: 'Which side?', form: { fields: [{ name: 'side', type: 'select', options: ['left', 'right'] }] } };
},onAction(name, args, person) runs when the person chooses one of now.actions with world.act(name, args) and returns an answer in the same way. act resolves with 'requested' for an action in now.actions and with 'not-allowed' for any other name.
Slow answers. A real world takes time to answer. An async onMessage makes the fake one wait as well and lets you see your view in its waiting state:
onMessage: async (message) => {
await new Promise((resolve) => setTimeout(resolve, 2000)); // two seconds of "thinking"
return `You said ${message.text}`;
},Every answer of a fake world arrives 200 ms after the message even without an async function.
Fake agents
A view can also show an agent (a lone agent the person talks to) instead of a world. A fake agent takes the same fields without members and roles:
const helper = await connectToHost({
fake: {
agent: {
name: 'Painter',
data: { mood: 'happy' },
onMessage: (message) => ({ image: drawPicture(message.text), text: 'Here it is' }),
},
},
});The answers of an agent carry every field an answer can hold (pictures and files included) and have isSystem: false.
Failures
With failNext: true the next message the person sends fails. send resolves with 'failed', the message gets status: 'failed' and its retry() delivers it. failNext applies once and the kit then resets it to false. To fail again later, assign true to it on the same object:
const office = { name: 'Post office', failNext: true };
// ...later, from a test button or the console:
office.failNext = true;A fake world cannot reproduce every case of the webapp. The table lists how to test each one:
| In the webapp | With a fake world |
|---|---|
a call that rejects with 'failed' | Never happens. Call your error handling with a made-up error such as handle({ code: 'failed' }). |
canSend false | Only for a moment while a fake agent connects or a message is pending. Keep the turn in data. |
'declined' or 'unavailable' from askFor and 'unavailable' from identity | Never happens because both calls resolve. Call your catch branch with { code: 'declined' }. |
'not-allowed-verb' (an older webapp) | Never. Call your catch branch with { code: 'not-allowed-verb' }. |
'too-big' | Happens as in the webapp with a file over 20 MB such as new Blob([new Uint8Array(21 * 1024 * 1024)]). |
openProfile | Shows no card and resolves to true for the id of the world or of a member and to false for any other id. |
The back button and setPath | Both calls do nothing. Call your back handler yourself and open your page at the path you want to test. |
Older messages (loadMore) | Resolves with 0. |
A world that ends (status: 'ended') | Not available. |
Scenarios worth testing
A view that works on one well-behaved world often breaks on the others. Keep a few fake worlds side by side and check your view with each one:
- The empty world has only a
namewith no data, nonowand no members. The view renders a sensible empty state and readsworld.now?.textbecausenowcan benull. - The busy world with data every 100 ms, thirty members with long names and a long conversation tests whether the view stays smooth and wraps long text.
- The slow world answers after five seconds and shows whether the view signals that it is waiting.
- The failing world (
failNext: true) tests that the person sees the failure and can retry. - The rich world answers with several pictures, a file with no name, a video, a chart and a message of a member (
from). Every message must render correctly. - The world that hides who wrote it (
showsSenders: false) must show no names next to the messages. - The phone (
webapp: { insets: { top: 0, right: 0, bottom: 34, left: 0 }, keyboard: 300 }) must keep the message box visible. - The other theme and language use
webapp: { theme: 'dark', language: 'it' }. - Nothing allowed (
webapp: { allowed: [] }) shows whether the view asks for the feature and offers an alternative.
While you build, a query parameter in the address of your page can choose the scenario:
// fakeWorlds.js: one fake world per scenario.
export const SCENARIOS = { empty: { name: 'Empty' }, busy: busyWorld, slow: slowWorld, failing: failingWorld };// main.js, while building: http://localhost:5173/?scenario=slow
import { SCENARIOS } from './fakeWorlds.js';
const scenario = new URLSearchParams(location.search).get('scenario') || 'busy';
const world = await connectToHost({ fake: { world: SCENARIOS[scenario] } });Automated tests
The kit runs in a browser and the tests of your view run in one too. A browser-testing tool such as Playwright opens your page with a scenario, acts as the person and checks what appears. This site tests its own examples in the same way:
// tests/view.spec.js (Playwright)
import { test, expect } from '@playwright/test';
test('a failed message can be retried', async ({ page }) => {
await page.goto('http://localhost:5173/?scenario=failing');
await page.getByRole('button', { name: 'Send a letter' }).click();
await expect(page.getByText('Not delivered. You can retry.')).toBeVisible();
await page.getByRole('button', { name: 'Retry' }).click();
await expect(page.getByText('Delivered: letter')).toBeVisible();
});Switching to the real webapp
In the webapp the same call without fake resolves with the real world:
const world = await connectToHost();Most projects keep the fake worlds during development and leave them out of the published site. A dynamic import behind import.meta.env.DEV keeps them out of the production build of a bundler such as Vite:
// While building (npm run dev): a fake world. Built for the webapp: the real one.
const options = import.meta.env.DEV
? { fake: { world: (await import('./fakeWorlds.js')).SCENARIOS.busy } }
: {};
const world = await connectToHost(options);In React, pass the same options to useWorld(options).
Pitfall
Do not choose the fake world by testing whether your page is inside a frame (window.parent === window). Anyone who opened the published page alone at its address would then see a fake world as if it were real. Outside the webapp show a message instead (Errors).
Then write the address of your development server in the Own view field of one of your worlds and try your view in the real webapp (Going live). The real webapp differs from a fake world in eight ways: (1) answers take longer, (2) canSend follows the turn of the person, (3) the person accepts the view in a consent dialog the first time, (4) the view reloads after a yes to askFor, (5) me has only the fields the person ticked, (6) the names of members arrive a moment after the members, (7) older messages can be loaded and (8) a file reaches the world without being read when none of its agents takes files.
Next steps
- Debugging: the tools to inspect your view and the common mistakes.
- Going live: your view on your own server with its address in the Own view field of your world.
- Reference: Fake worlds.
- Recipes: A fake world that changes over time, Test failures with a fake world.