How do I debug my lightning component?
General Tools and settings:
- use Chrome + built in Dev Tools + Lightning Component Inspector
- be sure debug mode is enabled in your org (Setup: Lightning Components)
- be sure caching is disabled in your org (Setup: Session Settings -> uncheck "Enable secure and persistent browser caching to improve performance"
Techniques for most common use cases (be sure that Dev Tools in Chrome are open while testing):
check certain JavaScript code is called at all:
useconsole.log()
,console.debug()
,console.warn()
,console.error()
(different color visualizations) -> can output a variable value as wellcheck for invalid values only:
rather always log to the console you can doconsole.assert(myVar != 0)
to only show an error when assertion failsevaluate variables / context on a certain JavaScript code:
usedebugger;
(this will create a breakpoint in code execution) -> now use the console from Dev Tools while breakpoint is active.
You can write JavaScript to test value of variables, do function calls and check return types, overwrite JavaScript values, and so on. This is super powerful also developing your codeoutput the value of a more complex Object:
while code execution is paused on a breakpoint (see above) usecopy(JSON.stringify(myObjectToEvaluate));
in the Dev Tool console - this will copy the value as JSON to your clipboard and you can process/inspect text based valuemeasure code execution time between two dedicated "anchors": use
console.time("identifier"); [code to execute] console.timeEnd("identifier");
check why code can not be saved or application is not loading at all: use the Salesforce Lightning CLI to lint your JavaScript code (very useful to check against faulty structure like missing braces)
investigate runtime exceptions origin:
sometimes runtime exceptions show up you don't know exactly where they come from. Use "Pause on Exception"-Button under the "Sources"-Tab in Dev Tools - inside the panel "Call Stack" check if you can identify classes from your code.
As code execution is paused you have the same behavior as a manual breakpoint: on every entry you are in the right JavaScript context so you can evaluate all values at that certain code execution time. Add some additional breakpoints (by clicking the line number in the Dev Tools) and you will always pause the code on certain area (like to check what values are before the exception raises or pause on code you can't write a debugger-statement by yourself)mock data returned from you Apex controller: use the Lightning Components Inspector "Action" Tab and overwrite the result coming back from the server the next time
For sure there are much more useful tools and scenarios, so it is definitely worse checking what Chrome Dev Tools can do for you. Also what scenarios Lightning Component Inspector is used for.