How to Debug Your Cypress Tests
To debug your Cypress tests, you can either use the debugger
keyword in a callback, use Chrome's DevTools, or use the built-in cy.debug
command. Let's have a look at each one by one.
Using the debugger
Since Cypress runs inside a browser, you have access to the reserved debugger
keyword. This means you can debug your Cypress tests using this keyword. Now you may be tempted to add a debugger
to a new line where you want to stop code execution, like this:
cy.get('button');
// Trying to stop code execution to debug the previous command
debugger;
Unfortunately, however, this wouldn't work. The reason being is that Cypress works asynchronously. This means by the time your browser comes across the debugger
keywords, the previous commands haven't been executed yet.
In order to get around this, we want to call the debugger
in a callback function, so we can translate the above code example to the following:
cy.get('button').then($button => {
debugger;
});
We can chain a then
callback from the command to make sure Cypress has finished the execution. We can then safely call debugger
inside the callback to get the desired behavior.
Using cy.debug
Cypress also has a built-in command for debugging, cy.debug
, which can be called from another Cypress command to get additional information about it:
cy.get('button').debug();
// Donβt display the command in the command log:
cy.get('button').debug(false);
// Call cy.debug on its own
cy.debug();
Just as the debugger
keyword, it will stop code execution wherever you call .debug
, additionally, you will get some debug information logged to the console about the command you chain cy.debug
from.
You can also call cy.debug
on its own, in this case, however, you will only get code execution stopped. If you don't disable logging, the values logged to the console will be undefined
, since you haven't attached it to any other command.
Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: