Bird
Raised Fist0
Cypresstesting~8 mins

Code coverage plugin in Cypress - Framework Patterns

Choose your learning style10 modes available
Framework Mode - Code coverage plugin
Folder Structure
  cypress/
  ├── e2e/                  # Test specs
  │   └── example.cy.js
  ├── support/              # Support files and commands
  │   ├── commands.js
  │   └── e2e.js
  ├── fixtures/             # Test data files
  │   └── example.json
  └── coverage/             # Code coverage reports (generated)

  cypress.config.js         # Cypress configuration file
  package.json              # Project dependencies and scripts
  .nycrc.json               # NYC (Istanbul) coverage config
  
Test Framework Layers
  • Test Specs (cypress/e2e/): Contains test files that run user scenarios and trigger code execution.
  • Support Layer (cypress/support/): Custom commands and setup code, including importing the coverage plugin.
  • Code Coverage Instrumentation: The app code is instrumented (usually via a bundler plugin or preprocessor) to collect coverage data during tests.
  • Configuration: cypress.config.js configures Cypress and integrates the coverage plugin.
    .nycrc.json configures coverage report formats and thresholds.
  • Coverage Reports (cypress/coverage/): Generated after tests run, showing which code lines were executed.
Configuration Patterns
  • cypress.config.js: Import and setup the coverage plugin in the setupNodeEvents function.
    import { defineConfig } from 'cypress'
    import codeCoverageTask from '@cypress/code-coverage/task'
    
    export default defineConfig({
      e2e: {
        setupNodeEvents(on, config) {
          codeCoverageTask(on, config)
          return config
        },
        baseUrl: 'http://localhost:3000',
      },
    })
  • cypress/support/e2e.js: Import the coverage support commands.
    import '@cypress/code-coverage/support'
  • .nycrc.json: Configure coverage report formats and thresholds.
    {
      "extends": "@istanbuljs/nyc-config-babel",
      "all": true,
      "reporter": ["html", "text-summary"],
      "check-coverage": true,
      "branches": 80,
      "functions": 80,
      "lines": 80,
      "statements": 80
    }
  • Environment Handling: Use baseUrl in Cypress config to switch between dev, staging, prod. Credentials can be stored securely using environment variables or Cypress.env.
Test Reporting and CI/CD Integration
  • Coverage Reports: After tests run, coverage reports are generated in cypress/coverage/ in HTML and text-summary formats. These reports show which lines of code were executed during tests.
  • CI/CD Integration:
    • Run Cypress tests in CI pipelines (GitHub Actions, Jenkins, GitLab CI).
    • Collect coverage reports as artifacts.
    • Fail builds if coverage thresholds are not met (configured in .nycrc.json).
    • Publish coverage reports to dashboards or code quality tools.
  • Example GitHub Actions Step:
    steps:
      - uses: actions/checkout@v3
      - uses: cypress-io/github-action@v5
        with:
          start: npm start
          wait-on: 'http://localhost:3000'
          wait-on-timeout: 60
      - run: npm run test:e2e
      - run: npm run coverage:report
Best Practices
  • Instrument Code Before Tests: Ensure your app code is instrumented for coverage before running Cypress tests.
  • Use Official Plugins: Use @cypress/code-coverage plugin for reliable integration.
  • Keep Coverage Thresholds Realistic: Set coverage thresholds that encourage improvement but allow incremental progress.
  • Separate Coverage from Functional Tests: Run coverage-enabled tests in dedicated CI jobs to avoid slowing down all tests.
  • Secure Sensitive Data: Never hardcode credentials; use environment variables or secure vaults.
Self Check

Where in this folder structure would you add a new custom command to collect additional coverage metrics during tests?

Key Result
Integrate @cypress/code-coverage plugin with Cypress tests to collect and report code coverage efficiently.

Practice

(1/5)
1. What is the main purpose of the Cypress code coverage plugin?
easy
A. To show which parts of your code are tested and which are not
B. To speed up test execution time
C. To automatically fix bugs in your code
D. To generate user interface screenshots

Solution

  1. Step 1: Understand code coverage concept

    Code coverage helps identify which lines or branches of code are executed during tests.
  2. Step 2: Match purpose with plugin function

    The Cypress code coverage plugin tracks and reports tested vs untested code parts.
  3. Final Answer:

    To show which parts of your code are tested and which are not -> Option A
  4. Quick Check:

    Code coverage = tested vs untested code [OK]
Hint: Code coverage = shows tested and missed code parts [OK]
Common Mistakes:
  • Thinking it speeds up tests
  • Believing it fixes bugs automatically
  • Confusing it with screenshot tools
2. Which file should you modify to enable the Cypress code coverage plugin support?
easy
A. cypress/support/e2e.js
B. cypress/fixtures/data.json
C. package.json
D. cypress.config.js

Solution

  1. Step 1: Identify where plugin support code goes

    The plugin support code is added in the support file to load before tests run.
  2. Step 2: Choose correct support file path

    By default, Cypress uses cypress/support/e2e.js for test support setup.
  3. Final Answer:

    cypress/support/e2e.js -> Option A
  4. Quick Check:

    Support file = cypress/support/e2e.js [OK]
Hint: Support code goes in cypress/support/e2e.js [OK]
Common Mistakes:
  • Modifying cypress.config.js only
  • Changing package.json for plugin support
  • Editing fixture files for plugin setup
3. Given this snippet in cypress/support/e2e.js:
import '@cypress/code-coverage/support';
What will happen when you run your tests?
medium
A. Tests will fail due to missing plugin installation
B. No effect; code coverage requires config changes only
C. Code coverage data will be collected during tests
D. Tests will run but coverage report will be empty

Solution

  1. Step 1: Understand import statement effect

    Importing '@cypress/code-coverage/support' enables coverage collection hooks.
  2. Step 2: Recognize plugin behavior during test run

    This import activates coverage tracking so data is gathered as tests run.
  3. Final Answer:

    Code coverage data will be collected during tests -> Option C
  4. Quick Check:

    Import support = coverage data collected [OK]
Hint: Importing support enables coverage collection [OK]
Common Mistakes:
  • Assuming import alone fails tests
  • Thinking config changes alone enable coverage
  • Believing coverage report is empty without extra steps
4. You added the code coverage plugin but your coverage report is empty after tests run. What is the most likely cause?
medium
A. You did not write any tests
B. You forgot to instrument your app code with the coverage tool
C. You imported the plugin support file twice
D. You ran tests in headless mode

Solution

  1. Step 1: Understand coverage instrumentation

    Coverage requires your app code to be instrumented to track executed lines.
  2. Step 2: Identify missing instrumentation effect

    Without instrumentation, coverage plugin cannot detect which code ran, so report is empty.
  3. Final Answer:

    You forgot to instrument your app code with the coverage tool -> Option B
  4. Quick Check:

    Missing instrumentation = empty coverage report [OK]
Hint: Instrument app code to get coverage data [OK]
Common Mistakes:
  • Assuming no tests means empty report
  • Thinking duplicate imports cause empty report
  • Believing headless mode disables coverage
5. You want to improve your test suite by using the Cypress code coverage plugin. Which steps should you follow to get a working coverage report? Select the correct sequence.
hard
A. Instrument app code, run tests, install plugin, import support in e2e.js, check report
B. Run tests, install plugin, import support in e2e.js, instrument app code, check report
C. Import support in e2e.js, run tests, install plugin, instrument app code, check report
D. Install plugin, instrument app code, import support in e2e.js, run tests, check report

Solution

  1. Step 1: Install the code coverage plugin

    First, add the plugin package to your project dependencies.
  2. Step 2: Instrument your application code

    Modify your app build to include coverage instrumentation for tracking.
  3. Step 3: Import the plugin support file in cypress/support/e2e.js

    This enables coverage hooks during test execution.
  4. Step 4: Run your Cypress tests

    Tests will now collect coverage data as they execute.
  5. Step 5: Check the generated coverage report

    Review which code was covered and improve tests accordingly.
  6. Final Answer:

    Install plugin, instrument app code, import support in e2e.js, run tests, check report -> Option D
  7. Quick Check:

    Correct setup sequence = Install plugin, instrument app code, import support in e2e.js, run tests, check report [OK]
Hint: Install, instrument, import support, run tests, check report [OK]
Common Mistakes:
  • Running tests before installing plugin
  • Skipping instrumentation step
  • Importing support after running tests
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard