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
- Yarn
- pnpm
npm install --save-dev jest
yarn add --dev jest
pnpm add --save-dev jest
// jest.config.js
module.exports = {
testEnvironment: "@livepreso/content-testing/jest/environment",
setupFilesAfterEnv: ["@livepreso/content-testing/jest/setup"],
};
| Entry | What it does |
|---|---|
jest/environment | Loads the built deck before a spec runs. |
jest/environment-jsdom | The same, and renders content in jest's jsdom DOM. |
jest/setup | Registers 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
- Yarn
- pnpm
npm install --save-dev jest-environment-jsdom
yarn add --dev jest-environment-jsdom
pnpm add --save-dev jest-environment-jsdom
Example: testing actions​
fee-actions.js defines a get query and a set mutation. The spec calls both.
- fee-actions.js
- delivery.spec.js
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,
},
});
const { deck, modes } = require("@livepreso/content-testing/jest");
it("should read back the fee that was set", 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");
});
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.
| Mode | Reproduces | Channels | Editable |
|---|---|---|---|
modes.preso.prepping | A preso being prepped, with editables showing | personal, everyone | personal |
modes.preso.previewing | Prep's preview of how a slide looks when presented | personal, everyone | personal |
modes.preso.presenting | A preso being presented to a customer | personal, everyone | personal |
modes.preso.reviewing | A preso after it has been presented | personal, everyone | none |
modes.preso.addingUserTemplate | A user template dropped into a preso | personal, everyone | personal, everyone |
modes.preso.addingCustomSlide | A template dropped into a preso as a custom slide, before the upload | personal, everyone | personal, everyone |
modes.preso.addedCustomSlide | The same custom slide, once it is uploaded | personal, everyone | personal, everyone |
modes.preso.addingTemplatePreview | A template in the preso slide picker | everyone | none |
modes.presomanager.editing | PresoManager, editing the content every preso starts with | everyone | everyone |
modes.presomanager.previewing | PresoManager, with no content entered | everyone | everyone |
modes.presomanager.placingTemplate | A template placed as a slide in PresoManager, before publishing | everyone | everyone |
modes.presomanager.placedTemplate | The same slide, once it is published | everyone | everyone |
modes.presomanager.templatePreview | A template in the PresoManager template list | everyone | none |
modes.preset.previewing | A preset preview | everyone | none |
modes.share.online | A preso shared with a customer by link | personal, everyone | personal |
modes.share.remote | A preso a customer joined remotely from their browser | personal, everyone | personal |
modes.screenshot.thumbnail | A slide rendered for a thumbnail capture | personal, everyone | none |
modes.screenshot.pdf | A slide rendered for a PDF capture | personal, everyone | none |
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.
| Env | Keys |
|---|---|
appointment | id, begin, end |
tenancy | id, name, brand_colour, logo_cropped, logo_original, logo_background_colour |
user | id, 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.
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: () => "",
},
});
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:
| Property | Description |
|---|---|
code | The refusal code: a key from the deck's rules, or a built-in code such as invalid-input or takes-no-input. |
issues | One sentence per invalid argument. An empty array under every other code. |
operation | The query or mutation that refused, under the field's key, such as postage-fee.set. |
target | The key of the slide, section or template the call was made on, or null. |
input | The arguments it was called with. |
isFailure | true when the query or mutation threw, so the deck has a bug. |
The examples on this page use this field:
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();
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​
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");
});