Skip to main content

Unit tests

A unit test is an ordinary jest spec, so the code in a deck is tested the way any other JavaScript is. @livepreso/content-testing adds two things: a spec can load your built deck, and call the queries and mutations of its editable fields.

Setup​

npm install --save-dev jest
// jest.config.js
module.exports = {
testEnvironment: "@livepreso/content-testing/jest/environment",
setupFilesAfterEnv: ["@livepreso/content-testing/jest/setup"],
};
EntryWhat it does
jest/environmentLoads the built deck before a spec runs.
jest/environment-jsdomThe same, and renders content in jest's jsdom DOM.
jest/setupRegisters toBeRefused, and between tests puts the deck back to what the spec file set up.

jest/environment calls fields but cannot render a slide. To render content, name jest/environment-jsdom in testEnvironment, or set it for one file:

/**
* @jest-environment @livepreso/content-testing/jest/environment-jsdom
*/

jest/environment-jsdom needs jest-environment-jsdom installed:

npm install --save-dev jest-environment-jsdom

Example: testing actions​

fee-actions.js defines a get query and a set mutation. The spec calls both.

import { defineActions } from "@livepreso/webpack-deck";

export const fee = defineActions({
defaultState: "",
mime: "text/plain",

queries: {
/**
* The fee as the slide shows it.
*
* @returns {string}
*/
get: ({ state }) => state,
},

mutations: {
/**
* Quote a postage fee.
*
* @param {object} args
* @param {object} args.input
* @param {string} args.input.text the fee as it shows on the slide
*/
set: ({ input }) => input.text,
},
});

The spec calls get and set because those are the names in defineActions. bindActions attaches the field to the delivery slide as postage-fee.

The deck is the one jest runs in, found from the directory it was started in, so a spec only has to pass a target key.

deck​

A target is one slide, one section or one template - the three things a deck declares fields on. See Editables.

.openTarget(key)​

The slide, section or template with this key. Which keys exist depends on the mode. Nothing loads until you call a field operation on the target.

Returns: the target.

Throws: on the first operation, when no target has this key, under the code unknown-target.

deck.setMode(modes.preso.prepping);

deck.openTarget("pricing/delivery"); // the slide
deck.openTarget("pricing"); // the section that contains it
deck.openTarget("welcome"); // the welcome slide

// A template is reachable only on a mode that places one.
deck.setMode(modes.presomanager.placingTemplate);

deck.openTarget("price-card"); // the template, by its key in project.yaml
const card = deck.openTarget("price-card");

card; // { openField }

.setMode(mode)​

Chooses which page of the app the deck reproduces. A deck has one mode at a time, and every target opened from it uses that mode.

Returns: undefined

Throws: on a mode that doesn't exist.

deck.setMode(modes.presomanager.editing);

A mode reproduces one page of the application: Prep, PresoManager, a share link, a screenshot. A slide behaves differently in each. Prep and PresoManager edit different stores, a share shows the finished preso to a customer, and a screenshot renders the slide for capture.

Pick the mode your test is about. The same field is editable in modes.presomanager.editing and read-only in modes.share.online.

The Channels column lists the channels a mode makes available, and Editable says which of them a mutation can write. Where a mode makes neither of a field's channels available, openField throws as if the field did not exist.

ModeReproducesChannelsEditable
modes.preso.preppingA preso being prepped, with editables showingpersonal, everyonepersonal
modes.preso.previewingPrep's preview of how a slide looks when presentedpersonal, everyonepersonal
modes.preso.presentingA preso being presented to a customerpersonal, everyonepersonal
modes.preso.reviewingA preso after it has been presentedpersonal, everyonenone
modes.preso.addingUserTemplateA user template dropped into a presopersonal, everyonepersonal, everyone
modes.preso.addingCustomSlideA template dropped into a preso as a custom slide, before the uploadpersonal, everyonepersonal, everyone
modes.preso.addedCustomSlideThe same custom slide, once it is uploadedpersonal, everyonepersonal, everyone
modes.preso.addingTemplatePreviewA template in the preso slide pickereveryonenone
modes.presomanager.editingPresoManager, editing the content every preso starts witheveryoneeveryone
modes.presomanager.previewingPresoManager, with no content enteredeveryoneeveryone
modes.presomanager.placingTemplateA template placed as a slide in PresoManager, before publishingeveryoneeveryone
modes.presomanager.placedTemplateThe same slide, once it is publishedeveryoneeveryone
modes.presomanager.templatePreviewA template in the PresoManager template listeveryonenone
modes.preset.previewingA preset previeweveryonenone
modes.share.onlineA preso shared with a customer by linkpersonal, everyonepersonal
modes.share.remoteA preso a customer joined remotely from their browserpersonal, everyonepersonal
modes.screenshot.thumbnailA slide rendered for a thumbnail capturepersonal, everyonenone
modes.screenshot.pdfA slide rendered for a PDF capturepersonal, everyonenone

Writing to a channel the mode cannot edit is refused with the code read-only. A template can only be edited where the mode shows it as an instance or as a custom version of one. Each mode applies the same body classes as the page it reproduces.

The same set succeeds in modes.presomanager.editing and is refused in modes.share.online:

it("should set the fee in PresoManager", async () => {
deck.setMode(modes.presomanager.editing);

const fee = deck.openTarget("pricing/delivery").openField("postage-fee");

await fee.set({ text: "$12" });

expect(await fee.get()).toBe("$12");
});

it("should refuse a fee on a share link", async () => {
deck.setMode(modes.share.online);

const fee = deck.openTarget("pricing/delivery").openField("postage-fee");

await expect(fee.set({ text: "$12" })).rejects.toThrow(/read-only/);
});

.setContext(context)​

Replaces the context. Keys from an earlier call are dropped, though a value a field already wrote is kept.

Returns: undefined

deck.setContext({ order: { express: true } });

.setCmsVals(cmsVals)​

Replaces the CMSVal keys the deck renders with.

Returns: undefined

Throws: in a mode that has no cmsvals, such as modes.presomanager.templatePreview.

deck.setCmsVals({ "delivery-heading": "Delivery" });

.setFeeds(feeds)​

Sets the feed data the slide reads, keyed by feed name.

Returns: undefined

Throws: when the name is not a feed the project file declares. The message lists the feeds that are.

deck.setFeeds({ rates: { standard: "$12" } });

.setEnvs(envs)​

Sets envs, the values the app provides to a deck, keyed by env name. A spec states each env in full, and an env it leaves out is absent.

EnvKeys
appointmentid, begin, end
tenancyid, name, brand_colour, logo_cropped, logo_original, logo_background_colour
userid, first_name, last_name, email, profile

Returns: undefined

Throws: on an unknown env.

deck.setEnvs({ user: { first_name: "Sam" } });

target​

.openField(name)​

The field for one editable on this target. It has a function for each query and mutation in the editable's defineActions. name matches the end of the field's key, so "postage-fee" finds delivery-postage-fee.

Returns: the field. Call its operations directly, as in deck.openTarget(key).openField(name).get().

Throws: when two fields end with name, naming both, and when none does, listing the fields that exist.

const fee = slide.openField("postage-fee");

fee.get(); // a promise of the value

field​

.<query>() and .<mutation>(input)​

The field has one function for each query and mutation in its defineActions, with the same name.

An operation takes an argument only if its @param lines describe one. Passing an argument to a mutation with no @param input is refused with takes-no-input.

Returns: a query returns a promise of its value, and a mutation a promise that resolves to undefined once the write is applied.

fee-actions.js
export const fee = defineActions({
defaultState: "",

queries: {
get: ({ state }) => state,

/**
* Whether the fee is inside what the customer will pay.
*
* @param {object} args
* @param {object} args.input
* @param {number} args.input.budget dollars the customer will pay
* @returns {boolean}
*/
withinBudget: ({ state, input }) => Number(state.replace("$", "")) <= input.budget,
},

mutations: {
set: ({ input }) => input.text,
clear: () => "",
},
});
fee.spec.js
await fee.set({ text: "$18" }); // undefined
await fee.get(); // "$18"
await fee.withinBudget({ budget: 20 }); // true

await fee.clear(); // undefined
await fee.get(); // ""

Refusals​

A query or a mutation can be refused. Before it runs, the deck checks the call against its rules and against the arguments the @param lines describe. If a check fails, the call throws a RefusedError with a code and a sentence saying why, and the field keeps its old value.

A refusal is the expected result of a bad call, so a test asserts it. The code failed is the exception: the query or mutation threw, isFailure is true, and the deck has a bug.

A RefusedError has these properties:

PropertyDescription
codeThe refusal code: a key from the deck's rules, or a built-in code such as invalid-input or takes-no-input.
issuesOne sentence per invalid argument. An empty array under every other code.
operationThe query or mutation that refused, under the field's key, such as postage-fee.set.
targetThe key of the slide, section or template the call was made on, or null.
inputThe arguments it was called with.
isFailuretrue when the query or mutation threw, so the deck has a bug.

The examples on this page use this field:

fee-actions.js
import { defineActions, defineRule } from "@livepreso/webpack-deck";

const fitsTheLabel = defineRule({
description: "A fee shows in six characters or fewer.",
check: ({ state }) => state.length <= 6,
});

export const fee = defineActions({
defaultState: "",
rules: { "too-long": fitsTheLabel },
mutations: {
/**
* Quote a postage fee.
*
* @param {object} args
* @param {object} args.input
* @param {string} args.input.text the fee as it shows on the slide
*/
set: ({ input }) => input.text,
},
});

This field can be refused two ways. too-long comes from the rule: the fee is seven or more characters. invalid-input comes from the @param lines: text is missing or is not a string.

toBeRefused(code)​

Passes when the call was refused. With a code, it passes only when the refusal has that code. Without one, any refusal passes except failed, which throws, because the deck has a bug rather than a rule to assert.

await expect(fee.set({ text: "twelve dollars" })).toBeRefused("too-long");
await expect(fee.set({ text: 12 })).toBeRefused();
warning

toBeRefused must be called with await, or it will always pass.

Asserting errors​

A rule's code says why: whoever wrote the rule named it, so too-long tells you which limit was broken.

Every argument problem shares the code invalid-input, whether a key is missing or has the wrong type. The sentences are in issues, so assert on them to tell the cases apart:

await expect(fee.set({ text: 12 })).rejects.toMatchObject({
code: "invalid-input",
issues: ["text must be a string"],
});

A full example​

fee.spec.js
const { deck, modes } = require("@livepreso/content-testing/jest");

let fee;

beforeEach(() => {
deck.setMode(modes.presomanager.editing);

// openTarget and openField do no work until get or set is called, so
// every test below can reuse this field.
fee = deck.openTarget("pricing/delivery").openField("postage-fee");
});

it("should set a fee of six characters or fewer", async () => {
await fee.set({ text: "$12" });

expect(await fee.get()).toBe("$12");
});

it("should refuse a fee of seven characters or more", async () => {
await expect(fee.set({ text: "twelve dollars" })).toBeRefused("too-long");
});

it("should refuse a fee that is not a string", async () => {
await expect(fee.set({ text: 12 })).toBeRefused("invalid-input");
});