# How to track test coverage in Replit

- Tool: Replit
- Difficulty: Beginner
- Time required: 15-20 minutes
- Compatibility: All Replit plans (Starter, Core, Pro). Works with Python (coverage.py + pytest) and Node.js (nyc + jest/mocha).
- Last updated: March 2026

## TL;DR

You can track test coverage in Replit by running coverage.py for Python projects or istanbul/nyc for Node.js projects directly in the Shell tab. These tools measure which lines of your code are executed during tests and generate reports showing uncovered code. Add a coverage script to your .replit run command or package.json to integrate coverage tracking into your workflow.

## Measure Test Coverage in Replit to Find Untested Code

This tutorial walks you through setting up code coverage reporting in Replit so you can see exactly which parts of your codebase are tested and which are not. You will install a coverage tool, run your test suite with coverage tracking enabled, read the coverage report to identify untested code, and set a minimum coverage threshold to enforce quality standards. Coverage reports run entirely in the Shell and Console — no external services needed.

## Before you start

- A Replit account (free Starter plan works)
- A Replit App with existing tests (pytest for Python or jest/mocha for Node.js)
- Basic familiarity with the Replit Shell tab
- At least one test file in your project

## Step-by-step guide

### 1. Install the coverage tool in Shell

Open the Shell tab in your Replit workspace. For Python projects, install coverage.py which works with pytest, unittest, and any other Python test framework. For Node.js projects, install nyc (the command-line interface for istanbul) which works with jest, mocha, and other JavaScript test frameworks. Both tools are lightweight and install in seconds.

```
# For Python projects:
pip install coverage pytest

# For Node.js projects:
npm install --save-dev nyc
```

**Expected result:** The coverage tool installs successfully. Running 'coverage --version' or 'npx nyc --version' in Shell confirms the installation.

### 2. Run your tests with coverage tracking

Execute your test suite with coverage tracking enabled. For Python, prefix your test command with 'coverage run'. For Node.js, prefix with 'npx nyc'. The tool monitors which lines of source code are executed during the test run and records the results. After the tests complete, generate a coverage report that shows the percentage of lines covered per file.

```
# Python — run tests with coverage:
coverage run -m pytest
coverage report

# Python — see which specific lines are missed:
coverage report -m

# Node.js — run tests with coverage:
npx nyc mocha

# Node.js with jest (built-in coverage):
npx jest --coverage
```

**Expected result:** A table appears in the Shell showing each source file with its coverage percentage, number of statements, and missed lines.

### 3. Read the coverage report and identify gaps

The coverage report shows a table with columns for each file: Stmts (total statements), Miss (statements not executed during tests), Cover (percentage covered), and Missing (specific line numbers not covered). Focus on files with low coverage percentages and look at the Missing column to find exactly which lines need tests. Lines in error handling blocks, edge cases, and fallback logic are commonly uncovered. Aim for 80% or higher coverage on critical business logic.

```
# Example Python coverage output:
# Name                 Stmts   Miss  Cover   Missing
# --------------------------------------------------
# app/main.py            45     12    73%   23-28, 41-45
# app/utils.py           30      3    90%   15, 22, 29
# app/database.py        55     20    64%   30-50
# --------------------------------------------------
# TOTAL                 130     35    73%

# Lines 23-28 in main.py and 30-50 in database.py need tests
```

**Expected result:** You can read the coverage report and identify which files and line numbers need additional tests.

### 4. Add a coverage script for easy re-running

Create a reusable script so you can run coverage checks quickly. For Python, create a script or add the commands to your .replit run command. For Node.js, add a coverage script to your package.json. This makes it easy to re-run coverage after writing new tests without remembering the exact command syntax.

```
# Python — add to .replit:
run = "coverage run -m pytest && coverage report -m"

# Node.js — add to package.json scripts:
{
  "scripts": {
    "test": "jest",
    "coverage": "jest --coverage",
    "test:coverage": "nyc mocha"
  }
}

# Then run from Shell:
npm run coverage
```

**Expected result:** Running the coverage script produces a fresh coverage report. You can re-run it after writing new tests to see the coverage percentage increase.

### 5. Set a minimum coverage threshold

Enforce a minimum coverage standard by configuring the tool to fail if coverage drops below a threshold. For Python, add a .coveragerc configuration file. For Node.js with nyc, add configuration to package.json. When coverage drops below the threshold, the command exits with a non-zero code, which can block deployments if included in the build command. Start with a low threshold like 60% and increase it as you add more tests.

```
# Python — create .coveragerc:
[run]
source = app
omit = tests/*

[report]
fail_under = 70
show_missing = True

# Node.js — add to package.json:
{
  "nyc": {
    "check-coverage": true,
    "lines": 70,
    "functions": 70,
    "branches": 60,
    "reporter": ["text", "text-summary"]
  }
}
```

**Expected result:** Running coverage with a threshold configured causes the command to fail (exit code 2) if coverage is below the threshold, and succeed if it is above.

### 6. Generate an HTML coverage report for detailed review

For a visual, file-by-file view of which lines are covered, generate an HTML report. For Python, run coverage html which creates an htmlcov directory. For Node.js, configure nyc to output HTML. Open the HTML file in Replit's Preview pane or download it for local viewing. The HTML report highlights covered lines in green and uncovered lines in red, making it easy to spot gaps at a glance.

```
# Python — generate HTML report:
coverage html
# Opens htmlcov/index.html — view in Replit Preview or download

# Node.js — add HTML reporter:
{
  "nyc": {
    "reporter": ["text", "html"]
  }
}
# Run: npx nyc mocha
# Opens coverage/index.html
```

**Expected result:** An HTML coverage report is generated in the htmlcov/ or coverage/ directory with color-coded line-by-line coverage visualization.

## Complete code example

File: `test_app.py`

```python
# test_app.py — Example test file with coverage tracking
# Run with: coverage run -m pytest test_app.py && coverage report -m

import pytest

# ----- Source code to test -----
def calculate_grade(score):
    """Convert a numeric score to a letter grade."""
    if not isinstance(score, (int, float)):
        raise TypeError(f"Score must be a number, got {type(score).__name__}")
    if score < 0 or score > 100:
        raise ValueError(f"Score must be 0-100, got {score}")
    if score >= 90:
        return 'A'
    elif score >= 80:
        return 'B'
    elif score >= 70:
        return 'C'
    elif score >= 60:
        return 'D'
    else:
        return 'F'


def calculate_average(scores):
    """Calculate the average of a list of scores."""
    if not scores:
        return 0.0
    return sum(scores) / len(scores)


def get_class_summary(students):
    """Generate a summary of class performance."""
    if not students:
        return {'count': 0, 'average': 0, 'passing': 0}

    scores = [s['score'] for s in students]
    avg = calculate_average(scores)
    passing = sum(1 for s in students if s['score'] >= 60)

    return {
        'count': len(students),
        'average': round(avg, 1),
        'passing': passing
    }


# ----- Tests -----
class TestCalculateGrade:
    def test_a_grade(self):
        assert calculate_grade(95) == 'A'
        assert calculate_grade(90) == 'A'

    def test_b_grade(self):
        assert calculate_grade(85) == 'B'

    def test_c_grade(self):
        assert calculate_grade(75) == 'C'

    def test_d_grade(self):
        assert calculate_grade(65) == 'D'

    def test_f_grade(self):
        assert calculate_grade(50) == 'F'

    def test_invalid_type(self):
        with pytest.raises(TypeError):
            calculate_grade('ninety')

    def test_out_of_range(self):
        with pytest.raises(ValueError):
            calculate_grade(101)


class TestCalculateAverage:
    def test_normal_list(self):
        assert calculate_average([80, 90, 70]) == 80.0

    def test_empty_list(self):
        assert calculate_average([]) == 0.0


class TestGetClassSummary:
    def test_normal_class(self):
        students = [
            {'name': 'Alice', 'score': 90},
            {'name': 'Bob', 'score': 55},
        ]
        summary = get_class_summary(students)
        assert summary['count'] == 2
        assert summary['average'] == 72.5
        assert summary['passing'] == 1

    def test_empty_class(self):
        summary = get_class_summary([])
        assert summary['count'] == 0
```

## Common mistakes

- **Running coverage on test files instead of source files, inflating the coverage number** — undefined Fix: Configure coverage to only measure your source directory. In .coveragerc, set source = app and omit = tests/* to exclude test files from the report.
- **Aiming for 100% coverage and spending excessive time testing trivial code** — undefined Fix: Target 70-80% coverage for most projects. Focus on covering critical paths like data processing, authentication, and error handling rather than every getter and setter.
- **Generating coverage reports but never reading the Missing column to find uncovered lines** — undefined Fix: Always use coverage report -m (Python) or check the detailed output from jest --coverage. The Missing column tells you exactly which lines to write tests for.
- **Not adding coverage output directories to .gitignore, cluttering the repository** — undefined Fix: Add htmlcov/, coverage/, and .coverage to your .gitignore file before committing.

## Best practices

- Run coverage after every batch of new tests to track progress toward your coverage goal
- Focus coverage efforts on business logic and data processing — skip boilerplate and configuration
- Use coverage report -m (Python) to see exact uncovered line numbers, not just percentages
- Set a minimum coverage threshold and increase it gradually as your test suite grows
- Add htmlcov/ and coverage/ to .gitignore to keep generated reports out of version control
- Separate your coverage script from your main run command to avoid slowing down normal development
- Write tests for error handling paths — they are the most commonly uncovered code

## Frequently asked questions

### Does Replit have built-in code coverage?

No. Replit does not include a built-in coverage tool as of March 2026. You need to install coverage.py (Python) or nyc/jest (Node.js) via Shell and run them manually or through scripts.

### What is a good coverage percentage to aim for?

70-80% is a practical target for most projects. Critical business logic should be at 90%+. Aiming for 100% is rarely worth the effort since it forces you to test trivial code like getters and configuration files.

### Can I see coverage in a visual format?

Yes. Run 'coverage html' (Python) to generate an HTML report in the htmlcov directory. Open index.html in Replit's Preview pane to see color-coded line-by-line coverage with green (covered) and red (uncovered) highlighting.

### Does jest have built-in coverage support?

Yes. Run 'npx jest --coverage' to get a coverage report without installing nyc. Jest uses istanbul internally and produces the same style of coverage report with file-by-file breakdowns.

### Can I block deployments if coverage is too low?

Yes. Add a coverage check to your .replit deployment build command: build = ["sh", "-c", "coverage run -m pytest && coverage report --fail-under=70 && npm run build"]. The build will fail if coverage drops below 70%.

### Can Replit Agent write tests to improve coverage?

Yes. Ask Agent: 'Run coverage report and write tests to cover the uncovered lines in app/main.py. Focus on error handling paths and edge cases.' Agent v4 will read the coverage output and generate targeted tests.

### How do I exclude files from coverage tracking?

In Python, add an omit section to .coveragerc: omit = tests/*, migrations/*, setup.py. In Node.js with nyc, add an exclude array to the nyc config in package.json: ["tests", "node_modules"].

### What if my project needs a more sophisticated testing and coverage pipeline?

For complex projects that need multi-environment testing, coverage aggregation across services, and CI/CD integration, the RapidDev engineering team can set up a professional testing pipeline that goes beyond what single-tool coverage tracking provides.

---

Source: https://www.rapidevelopers.com/replit-tutorial/how-to-configure-code-coverage-reporting-in-replit-for-comprehensive-testing
© RapidDev — https://www.rapidevelopers.com/replit-tutorial/how-to-configure-code-coverage-reporting-in-replit-for-comprehensive-testing
