In Cypress, to skip tests when elements are not present, you can use conditional statements to verify the existence of elements and then determine whether to execute the test logic based on that. Here is a simple example to illustrate how to do this:
javascriptdescribe('Test Skipping Example', () => { it('Execute test if element exists, skip otherwise', () => { // Access the page we want to test cy.visit('http://example.com'); // Use Cypress's DOM query to check if elements exist cy.get('body').then(body => { if (body.find('.some-element').length > 0) { // If elements exist, execute the test cy.get('.some-element').should('have.text', 'expected text'); } else { // If elements do not exist, skip the test cy.log('Elements do not exist, skipping this test'); } }); }); });
In this example, we first use cy.visit to access the test page. Then, we use cy.get with the then method to check for the presence of elements matching the .some-element selector within the body element. If present, we proceed with the test checks; if not, we use cy.log to log a message and skip the subsequent assertions.
Note that this approach does not mark the test as skipped in the report; it simply conditionally skips executing the test logic. If you want the test to appear as skipped in the report, you can use Mocha's this.skip() method:
javascriptdescribe('Using this.skip to skip tests', () => { before(function () { // Check if elements exist; if not, skip all tests cy.visit('http://example.com'); cy.get('body').then(body => { if (body.find('.some-element').length === 0) { this.skip(); } }); }); it('Execute test 1 if not skipped previously', () => { // First test logic... }); it('Execute test 2 if not skipped previously', () => { // Second test logic... }); });
In the above example, we check for the existence of elements within the before hook function; if not present, we use this.skip() to skip all tests within the describe block. This will result in the skipped tests being visible in the test report. Note that this.skip() must be called within the body of it or before/after hook functions and cannot be used in arrow functions because arrow functions do not bind this.