When using Cypress for testing, you may sometimes want to create or debug a specific test case. Cypress offers several methods to run a single test case. Here are the specific methods:
Using the .only Method
You can mark a test case with .only so that Cypress runs only that specific test case. This works for both it and describe blocks.
For example, if you have multiple test cases:
javascriptdescribe('User Login Flow', () => { it('should correctly navigate to the login page', () => { // ... }); it.only('should allow users to log in successfully', () => { // Only this test case will be run }); it('should display an error message when users enter incorrect credentials', () => { // ... }); });
In the above example, only the test case marked with it.only ("should allow users to log in successfully") will be run.
Using Command-Line Flags
Another approach is to use the --spec command-line flag when running Cypress tests, which allows you to specify a particular test file to run.
shcypress run --spec "cypress/integration/login_spec.js"
However, if you want to run a specific test case within a file, Cypress does not currently support specifying a single test case directly via the command line. You need to combine .only with the --spec flag.
Important Notes
- When using
.only, remember to remove it after testing is complete, as committing code with.onlywill cause tests in the CI environment to run incomplete due to ignoring other test cases. - In Cypress's graphical interface, you can also click on the name of a single test case to run only that one.
Combining these methods allows you to focus more efficiently on a single test case during development or debugging.