Skip to main content

Fieldsets

The fieldsets hook builds the form a salesperson fills in when making a preso. The fieldsets object in a spec's arguments opens that form in the CDK and gives the spec the commands to drive it: set a field, change the customer, answer a warning, save.

Read end-to-end tests first for the setup. Fieldset specs use the same config and the same .e2e.mjs names.

Example​

The hook under test, from the deck's js/hooks/fieldsets.js:

export default function ({ Fieldset, Select }) {
return new Fieldset({
fields: [
new Select({
name: "service",
label: "Service",
options: [
{ label: "Delivery", value: "delivery" },
{ label: "Site visit", value: "site_visit" },
],
}),
new Select({ name: "delivery_window", label: "Delivery window", options: [] }),
],

onValidate: ({ fields }) => {
if (fields.service === "site_visit" && !fields.delivery_window) {
return { errors: { delivery_window: ["Pick a window for a site visit"] } };
}

return {};
},
});
}

The spec for it:

import { expect, test } from "@livepreso/content-testing/playwright";

test("should require a delivery window for a site visit", async ({ fieldsets }) => {
await fieldsets.selectCustomer({ key: "c1", id: 1, title: "Northside Builders" }, [
{ id: 5, name_first: "Rae", name_last: "Ito", email: "rae@example.com" },
]);

await fieldsets.choose("service", "site_visit");

const { isSaved, errors } = await fieldsets.save();

expect(isSaved).toBe(false);
expect(errors.delivery_window).toEqual(["Pick a window for a site visit"]);
});

The spec states the customer and the contacts, picks a select option the way a person would, then saves and reads the errors the save came back with.

Every example below shows the field's declaration from the hook first, then the spec that drives it.

What a spec states​

The CDK reads nothing from the deck's .cdk folder on a page a test opened: no request intercepts, no customer data and no contexts. A spec states every piece of data the form starts with, with the setters below.

A setter called before the first command takes effect when the form first builds. A setter called after it replaces that data and redraws the form.

SetterSets
selectCustomer(customer, contacts)Who the preso is for, which runs onCustomersChange
setAppointment(appointment)The appointment, which a hook reads at data.appointment
setUser(user)The user making the preso, which a hook reads at data.user
setContext(context)The context a saved preso carries, apart from field values
setFields(values)The value each field starts with, as context.fields
setServerUrl(url)The server a deck's requests go to, at data.urls
openSavedPreso()Opens a preso saved before, so isNewAppointment is false
open()Builds the form now, for a spec that reads nothing back

Every key on an appointment is optional. The times default to tomorrow at 10:00, running for an hour, so a field bounded to today or later accepts the default and most specs leave them out:

await fieldsets.setAppointment({ id: 77, title: "Kit review" });
await fieldsets.setUser({ id: 3, first_name: "Jo" });

State the times to test a date. They are the ISO strings the server sends, which is what a hook parsing a date gets in the app:

const BEGIN = new Date("2030-03-04T09:00:00Z");
const HOUR_MS = 60 * 60 * 1000;

await fieldsets.setAppointment({
begin: BEGIN.toISOString(),
end: new Date(BEGIN.getTime() + HOUR_MS).toISOString(),
});

setContext throws on a fields key. Pass field values to setFields:

await fieldsets.setFields({ kit_size: "large" });
await fieldsets.setContext({ depot: "north" });

A customer and a contact each take the keys the app sends. A key outside that list throws, and the message names the keys that are allowed.

Editing a saved preso​

openSavedPreso opens the form on a preso saved before, where the hook reads data.isNewAppointment as false.

The hook declares the field the saved preso carries a value for:

new Select({
name: "kit_size",
label: "Kit size",
options: [
{ label: "Small", value: "small" },
{ label: "Large", value: "large" },
],
});

The spec:

test("should keep the kit a saved preso was saved with", async ({ fieldsets }) => {
await fieldsets.openSavedPreso();
await fieldsets.setFields({ kit_size: "large" });

const { values } = await fieldsets.read();

expect(values.kit_size).toBe("large");
});

The form opens on those field values, and onLoad runs with the context as well. A spec that calls neither openSavedPreso nor save is making a new preso, where the hook reads isNewAppointment as true:

test("should prefill the kit on a new preso", async ({ fieldsets }) => {
const { values } = await fieldsets.read();

expect(values.kit_size).toBe("small");
});

A save makes the preso, so the form is editing a saved one from then on, as it is in the app:

await fieldsets.selectCustomer(CUSTOMER, [CONTACT]);
await fieldsets.save();

// The form rebuilt on the saved preso, so onLoad ran again with
// isNewAppointment false.
const { context } = await fieldsets.read();

Requests​

A spec answers the requests a hook makes with page.route, whichever way the hook makes them: fetch, superagent, axios, or anything else that reaches the network. The hook:

onLoad: async () => {
const { body } = await superagent.get("/api/kits/").query({ depot: 7 });

return { state: { kit_size: { options: body.results.map(({ id, title }) => ({ label: title, value: id })) } } };
},

The spec routes it:

await page.route("**/api/kits/?depot=7", (route) =>
route.fulfill({ json: { results: [{ id: 1, title: "Cement mixer" }] } }),
);

No request leaves the machine. Any request a spec left unrouted comes back 404 from the test itself, whether the deck asked the server at data.urls or one of its own, and they are listed when the test ends:

The following requests were made and not intercepted with route:

GET https://example.com/api/kits/?depot=7

Each came back 404 from the test. Route them to state what the server returns.

A deck reads the server it calls at data.urls.api. The test takes it from the first server in the deck's project file, and uses https://example.com where the project file doesn't list one. To set it explicitly:

await fieldsets.setServerUrl("https://sales.acme.test");

Setting values​

set, fill, choose and click simulate a person using the form. A field's type decides how its value is kept, so a spec passes the value and nothing else.

Each command runs onBeforeChange and then onChange, with the same delay typing has. Each resolves once those hooks finish, with the form as read() returns it.

Before a save(), a spec states a customer and at least one contact. Without them the save stops. A spec asserts every validation rule through a save.

.fill(name, text)​

Types into a text field. The hook declares the field:

new Input({ name: "site_contact", label: "Site contact" });

The spec:

await fieldsets.fill("site_contact", "Rae Ito");

.choose(name, option)​

Chooses one of a select's options by its value. The hook declares the options:

new Select({
name: "kit_size",
label: "Kit size",
options: [
{ label: "Small", value: "small" },
{ label: "Large", value: "large" },
],
});

The spec:

await fieldsets.choose("kit_size", "large");

Throws: when the select has no option with that value. The message lists the options.

.click(name)​

Clicks a button field, which runs the onClick the deck declared. The hook declares the button:

new Button({
name: "check_stock",
value: "Check stock",
onClick: () => ({ state: { check_stock: { disabled: true } } }),
});

The spec:

await fieldsets.click("check_stock");

Throws: when the field is not a button, or if the button is disabled.

.set(name, value)​

The general form. fill and choose call it. It takes any field that has a value. The hook declares a checkbox:

new Checkbox({ name: "needs_crane", label: "Needs a crane" });

The spec:

await fieldsets.set("needs_crane", true);

Throws: on a name the form has no field for. The message suggests the closest name, or lists all of them.

.setFieldState(name, change)​

Writes the field's state directly. Use it where a value alone cannot say what a person did, such as clearing a date. The hook declares the date field:

new DatePicker({ name: "delivery_date", label: "Delivery date" });

The spec:

await fieldsets.setFieldState("delivery_date", { date: "" });

Reading the form​

.read()​

Returns: a promise of the form as it is now.

KeyHolds
valuesThe value of each field, keyed by field name
stateThe state of each field: flags such as visible, disabled, and a select's options
errorsThe errors from the last save, keyed by field name
contextThe context the form has built
fieldsA list of { name, label, type }, one for each field
modalThe warning modal: { show, title, message, fieldKey }
isReadyWhether onLoad has finished

values has the same names and values that the deck's onValidate and onSave receive. Assert on it to check what the deck will see. Use state for what values leaves out.

The hook declares the fields:

new Select({
name: "kit_size",
label: "Kit size",
options: [
{ label: "Small", value: "small" },
{ label: "Large", value: "large" },
],
});
new Select({
name: "delivery_window",
label: "Delivery window",
options: [],
onLoad: () => ({ state: { delivery_window: { visible: false } } }),
});

The spec:

await fieldsets.choose("kit_size", "large");

const { values, state } = await fieldsets.read();

expect(values.kit_size).toBe("large");
expect(state.delivery_window.visible).toBe(false);
expect(state.kit_size.options.map(({ value }) => value)).toEqual(["small", "large"]);

A field inside a group or a row takes the group's name as a prefix, so the field window in the group delivery is delivery_window.

.debug()​

Prints every field with its type, value and flags, and returns the text it printed. Run it first on a deck you have not read.

await fieldsets.debug();
service          select         "site_visit"
kit_size select "small"
delivery_window input "" hidden
site_contact input "Rae Ito" errors: Required
check_stock button null disabled

The flags are hidden, disabled, loading, and errors: followed by the field's messages.

The lifecycle​

CommandRuns
selectCustomer(customer, contacts)onCustomersChange
set, fill, choose, clickonBeforeChange, then onChange
save()onValidate, then onSave

.selectCustomer(customer, contacts)​

Picks who the preso is for, which runs onCustomersChange. A preso in the app always has a customer and at least one contact, so this takes both, and it throws on an empty contact list.

A contact's name goes under name_first, as the server sends it. A slide spec's deck.setContacts uses first_name.

The hook enables the field once a customer has a contact:

new Input({ name: "site_contact", label: "Site contact", disabled: true }),

// on the Fieldset
onCustomersChange: ({ data }) => ({
state: { site_contact: { disabled: data.contacts.length === 0 } },
}),

The spec:

await fieldsets.selectCustomer({ key: "c2", id: 2, title: "Harbour Caterers" }, [
{ id: 9, name_first: "Lee", name_last: "Park" },
]);

const { state } = await fieldsets.read();

expect(state.site_contact.disabled).toBe(false);

.save()​

Runs onValidate and, when it passes, onSave. A spec asserts a rule by saving and reading errors off the result.

Returns: { isSaved, isValid, errors, context }, together with the form read() returns. isValid is the onValidate outcome, errors lists the messages under each field's name, and context is what onSave wrote.

A hook that throws fails the test, and the message names the one that threw: The fieldset's onValidate threw: ....

The hook declares a required field:

new Input({ name: "site_contact", label: "Site contact" });

// on the Fieldset
onValidate: ({ fields }) => {
if (!fields.site_contact) {
return { errors: { site_contact: ["Required"] } };
}

return {};
},

The spec:

await fieldsets.fill("site_contact", "");

const { isSaved, isValid, errors } = await fieldsets.save();

expect(isValid).toBe(false);
expect(isSaved).toBe(false);
expect(errors.site_contact).toEqual(["Required"]);

save() returns the context onSave wrote. Only what onSave returns under context reaches it:

new Select({
name: "kit_size",
label: "Kit size",
options: [
{ label: "Small", value: "small" },
{ label: "Large", value: "large" },
],

onSave: ({ value }) => ({ context: { kit: { size: value } } }),
});

The spec:

await fieldsets.choose("kit_size", "large");

const { isSaved, context } = await fieldsets.save();

expect(isSaved).toBe(true);
expect(context.kit.size).toBe("large");

onSave refuses the save by returning errors. Validation passed, so isValid is true and the messages come back under the field they name:

onSave: ({ fields }) => {
if (fields.kit_size === "large" && !fields.depot) {
return { errors: { depot: ["A large kit ships from a depot"] } };
}

return { context: { kit: { size: fields.kit_size } } };
},
const { isSaved, isValid, errors } = await fieldsets.save();

expect(isValid).toBe(true);
expect(isSaved).toBe(false);
expect(errors.depot).toEqual(["A large kit ships from a depot"]);

The warning modal​

When onBeforeChange returns a warning, the change stops and onChange waits. read() reports the warning under modal.

The hook declares the warning:

new Select({
name: "service",
label: "Service",
options: [
{ label: "Site visit", value: "site_visit" },
{ label: "Pickup", value: "pickup" },
],
onBeforeChange: ({ value }) => {
if (value === "pickup") {
return {
warning: {
title: "Change service",
message: "Chosen kits will be dropped. Continue?",
},
};
}
},
});

The spec:

test("should warn before dropping the chosen kits", async ({ fieldsets }) => {
await fieldsets.choose("service", "site_visit");

const { modal } = await fieldsets.choose("service", "pickup");

expect(modal).toMatchObject({ show: true, title: "Change service" });
});

continueChange() carries the change on, runs onChange and resolves with the form:

const { values } = await fieldsets.continueChange();

expect(values.service).toBe("pickup");

cancelChange() drops the change:

const { values, modal } = await fieldsets.cancelChange();

expect(values.service).toBe("site_visit");
expect(modal.show).toBe(false);

Fresh state​

Each test gets a new form and a freshly loaded hooks file. A variable at the top of the hooks file starts empty in every test, and a preso an earlier test saved is gone. Tests that share a worker do not affect one another.

Inside one test, reload() does the same. Use it where a spec runs one hook twice and each run must start from the empty variables. A preso the test saved is still there afterwards.

In this example, the hook keeps a count in a variable at the top of the file:

let itemCount = 0;

// in the fields array
new Button({
name: "add_item",
value: "Add item",
onClick: () => {
itemCount += 1;

return { state: { item_count: { value: itemCount } } };
},
});

The spec:

await fieldsets.click("add_item");
await fieldsets.reload();
await fieldsets.click("add_item");

const { values } = await fieldsets.read();

expect(values.item_count).toBe(1);

reset() is the other half: it starts a new preso from the context the form opened with and leaves the hooks file loaded, so a variable at the top of that file keeps what it had. The preso a save() made is dropped, so isNewAppointment is true again:

await fieldsets.set("depot", "north");
await fieldsets.reset();

const { values } = await fieldsets.read();

expect(values.depot).toBe("");

open() builds the form without reading anything back, for a spec that asserts what the form did as it built:

let fetched = 0;

await page.route("**/api/kits/", (route) => {
fetched += 1;

return route.fulfill({ json: { results: [] } });
});
await fieldsets.open();

expect(fetched).toBe(1);