Cypress part 6

Writing and Organizing Tests in Cypress

What You’ll Learn

  • How to organize Cypress tests and supported file types.
  • Writing tests with hooks, exclusions, and configurations.
  • Understanding test statuses.
  • Auto-watched files in Cypress.

Folder Structure

When adding a new project, Cypress scaffolds a default folder structure for E2E and Component testing:

E2E:

/cypress.config.js
/cypress/fixtures/example.json
/cypress/support/commands.js
/cypress/support/e2e.js

Component:

/cypress.config.js
/cypress/fixtures/example.json
/cypress/support/commands.js
/cypress/support/component.js
/cypress/support/component-index.html

Both:

Includes both E2E and Component files.

Configuring Folder Structure

Cypress allows customization of test, fixture, and support file locations through its configuration file.

.gitignore Recommendations

Exclude these files from source control:

  • cypress/screenshots/ (test screenshots)
  • cypress/videos/ (recorded test videos)
  • cypress/downloads/ (downloaded files)
  • cypress.env.json (sensitive environment variables)

Spec Files

By default, test files are stored in cypress/e2e and support:

  • .js, .jsx, .ts, .tsx, .coffee, .cjsx
  • ES2015 modules (import) and CommonJS (require)

Fixture Files

Stored in cypress/fixtures/, fixtures contain static data used in tests, typically with cy.fixture() for stubbing network requests.

Asset Files

Cypress generates asset folders such as:

  • cypress/downloads/
  • cypress/screenshots/
  • cypress/videos/

Cypress Cloud Integration

Store and replay test assets using Cypress Cloud for better debugging and collaboration.

Plugins File

The plugins file (cypress/plugins/index.js) runs in Node.js before test execution, allowing custom commands via cy.task().

Support Files

Pre-test setup code is stored in cypress/support/:

  • e2e.js (E2E tests)
  • component.js (Component tests)

Support files help define reusable behavior such as global hooks:

beforeEach(() => {
  cy.log('Runs before every test');
});

Writing Cypress Tests

Cypress is built on Mocha and Chai, supporting BDD and TDD styles:

describe('Math operations', () => {
  it('adds numbers', () => {
    expect(1 + 2).to.eq(3);
  });
  it('multiplies numbers', () => {
    expect(5 * 4).to.eq(20);
  });
});

Hooks

Cypress supports Mocha hooks for setup and cleanup:

  • before / beforeEach
  • after / afterEach

Debugging

Run Cypress with debug logs for troubleshooting:

DEBUG=cypress:* npx cypress open

Use Cypress Studio for a low-code test creation approach.

Cypress simplifies test writing and execution while offering flexibility in configuration and debugging.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *