Sub topic 9
Testing and debugging in Flow Builder
This chapter assumes you can build a basic screen flow, write an LWC with @api properties, and deploy components with Salesforce DX or the Developer Console. It covers how to test a flow screen component in Flow Builder, how to read debug output, and how to find the usual faults.
What you can test, and where
A flow screen component runs in three places during development. Each place tests different things.
| Place | What it tests | Limits |
|---|---|---|
| Jest unit tests | Component logic, `validate()`, events dispatched | No real flow runtime. You simulate inputs and listen for events. |
| Flow Builder Debug | Wiring, input values, output values, navigation | Runs the real flow. Changes made by the flow may be rolled back depending on the debug options. |
| Run from the org | Real user context, permissions, and layout | Slower to iterate. Needs a deployed component and an activated flow version. |
Start with Jest for logic, then use Debug for wiring, then run the activated flow as a real user.
Unit testing with Jest
The lightning/flowSupport module has no implementation in a Jest environment. The sfdx-lwc-jest tool provides a stub, so you can import FlowAttributeChangeEvent and the navigation events in tests. You test the component by setting its @api properties, simulating user input, and checking the events it dispatches.
The test below covers the QuantityPicker component from earlier chapters. It checks that a change event reaches the flow and that validate() blocks bad input.
import { createElement } from 'lwc';
import QuantityPicker from 'c/quantityPicker';
import { FlowAttributeChangeEventName } from 'lightning/flowSupport';
describe('c-quantity-picker', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
function setup() {
const element = createElement('c-quantity-picker', {
is: QuantityPicker
});
document.body.appendChild(element);
return element;
}
async function typeValue(element, value) {
const input = element.shadowRoot.querySelector('lightning-input');
input.dispatchEvent(new CustomEvent('change', { detail: { value } }));
await Promise.resolve();
}
it('reports a changed quantity to the flow', async () => {
const element = setup();
const handler = jest.fn();
element.addEventListener('lightning__flowattributechange', handler);
await typeValue(element, '3');
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0][0].detail.attributeName).toBe('quantity');
expect(handler.mock.calls[0][0].detail.attributeValue).toBe(3);
});
it('fails validation for zero', async () => {
const element = setup();
await typeValue(element, '0');
const result = element.validate();
expect(result.isValid).toBe(false);
expect(result.errorMessage).toBe('Enter a whole number greater than zero.');
});
it('passes validation for a positive whole number', async () => {
const element = setup();
await typeValue(element, '5');
expect(element.validate().isValid).toBe(true);
});
});Two details matter here. The FlowAttributeChangeEvent has the event name lightning__flowattributechange, and its detail holds attributeName and attributeValue. The test imports FlowAttributeChangeEventName only to show the module resolves. If your Jest setup has no mock for it, remove that import. The listener string is what the assertion needs.
Jest cannot tell you whether the flow accepts the value. A property that is missing from the meta.xml, or has the wrong type, passes every Jest test and still fails in the flow.
Debugging with Flow Builder Debug
Flow Builder has a Debug button on the canvas. It runs the flow in the builder and shows a log of every element, with the values of variables at each step.
Run a debug session
- Save the flow. Debug runs the saved version, not unsaved canvas edits.
- Click Debug.
- Set the input variables that the flow expects. Choose whether to run in rollback mode, which undoes record changes made by the run.
- Click Run.
- The flow displays its screens in the debug panel. Use the screen as a user would.
- Read the Debug Details panel for each element.
The panel lists the variables a screen sets. For a screen with your component, find the component's name and look at its output values after you click Next. Those are the values your FlowAttributeChangeEvent calls set.
What to check at each screen
- Do the input values shown in the details match what you passed in? If an input is empty, the problem is in the wiring or in the earlier flow elements, not in your component.
- Do the outputs hold the values you expect after the user acts? If an output is empty, check that the component dispatched the event with the correct
attributeName. - Did navigation happen when you expected? If clicking Next does nothing,
validate()is probably returningisValid: false.
Flow Builder does not reload your component code
Debug uses the component version deployed to the org. After you change the JavaScript, HTML, or meta.xml, deploy again, then reload the Flow Builder tab. A stale tab keeps the old component definition and the old property list. If you add a property to the meta.xml and it does not appear in the screen's configuration panel, reload the builder first.
Using the browser console
The flow screen runs inside Lightning Experience, so ordinary browser tools work. Open the developer tools while a debug session runs.
- Add
console.logcalls tohandleChange,validate(), and the navigation handlers. Remove them before you deploy to production. - Use the Sources panel to set breakpoints. In Chrome, enable Enable Custom Formatters or the Lightning Web Security setting that matches your org, and search for your component file name.
- Turn on debug mode for your user in Setup under Debug Mode. Without it, the platform serves minified code, which makes breakpoints hard to follow.
A small logging helper keeps messages easy to find:
const DEBUG = false;
export function log(...args) {
if (DEBUG) {
// eslint-disable-next-line no-console
console.log('[QuantityPicker]', ...args);
}
}Import log from a shared module, and flip DEBUG to true while you investigate.
The component lifecycle as the flow sees it
Many faults come from misreading when the component is created and destroyed. The flow creates a new instance of the component each time its screen is shown. When the user clicks Back and then Next again, the flow rebuilds the component and passes the stored values in as inputs.
This has three consequences for testing:
- Any state held only in a class field is lost when the user leaves the screen. Anything you want to keep must go out through a
FlowAttributeChangeEvent. - Your component must produce sensible output without user action. If the user clicks Next without touching the field, the flow still reads the values the component last reported. Report defaults in
connectedCallbackif the flow needs them. - Test the Back path by hand. Many components work on the first visit and fail on the second, because they ignore the inputs they receive on the second visit.
Common faults and how to find them
| Symptom | Likely cause | How to confirm |
|---|---|---|
| Component missing from the screen palette | `isExposed` is false, the `lightning__FlowScreen` target is missing, or the API version is too old | Read the meta.xml and redeploy |
| Property missing from the configuration panel | The `property` element has no matching `@api` field, or the name differs in case | Compare names in the meta.xml and the class |
| Output always empty in later elements | No `FlowAttributeChangeEvent` dispatched, or the `attributeName` is misspelled | Check Debug Details, then log in the handler |
| Flow does not stop on bad input | `validate()` is not marked `@api`, or it returns an object without `isValid` | Call `validate()` in a Jest test |
| Error `Cannot assign to read only property` | The component changed an array or object received from the flow | Copy the value before changing it |
| **Next** button does nothing | `validate()` returns `isValid: false` with no visible message | Return an `errorMessage` and log the result |
| Navigation event has no effect | The action is not in `availableActions` for that screen | Log `availableActions` |
Read-only inputs
Values that arrive from the flow are read-only inside the component. This matters most for collections and records. Changing a property of an incoming record, or pushing to an incoming array, throws an error. Copy first, then change the copy and report it:
handleSelect(event) {
const updated = { ...this.record, Name: event.detail.value };
this.record = updated;
this.dispatchEvent(new FlowAttributeChangeEvent('record', updated));
}For arrays, use [...this.records] or structuredClone, and for nested objects copy each level you change.
Types that do not match
Flow variables are strongly typed. If the meta.xml declares type="Integer" and the component sends a string, the flow may store nothing or show a conversion error. Convert in JavaScript before dispatching, as handleChange does with parseInt. Dates, times, and date-times arrive as strings, so parse and format them deliberately.
Testing the failure paths in Flow Builder
A flow test that only follows the happy path misses most defects. Run Debug at least once for each of these cases:
- The user leaves a required field empty and clicks Next.
- The user enters an invalid value, then corrects it.
- The user goes forward, clicks Back, and then goes forward again.
- An input from the flow is empty or null.
- The flow passes a very large collection, if your component displays lists.
Also run the activated flow as a user with a restricted profile. A component that works for an administrator can fail when Apex or object access is missing for a standard user.
Checklist before you hand off
- Jest tests pass for logic, validation, and emitted events.
- Debug runs show the expected inputs and outputs on every screen.
- Back and forward navigation preserves values.
- No
console.logcalls remain. - The meta.xml names match the
@apinames exactly. - A restricted-profile user completed the flow.
Exercise
A user clicks Next on your screen and nothing happens. Debug Details shows no error. Name two things to check, and say how each is confirmed.
Show answer
First, check whether validate() returned isValid false. Confirm it by calling validate() in a Jest test with the same input, or by logging its result in the browser console. Second, check whether NEXT is in availableActions for that screen, which a log of the property shows. If validate() fails, also make sure it returns an errorMessage so the user sees why.
Exercise
Your component receives an array of records from the flow and runs this.records.push(newRecord). The component throws an error in Debug. Why, and what is the fix?
Show answer
Values passed in from the flow are read-only. Push to a copy instead: create const updated = [...this.records, newRecord], store it in a class field, and dispatch new FlowAttributeChangeEvent('records', updated) so the flow receives the new array.