How to Run a Single Test with Mocha: Execute Specific Tests Instead of All in JavaScript

Mocha is one of the most popular JavaScript testing frameworks, widely used for testing Node.js applications and frontend code. When working on a project with a large test suite, running all tests every time you make a change can be slow and inefficient—especially when debugging a specific issue. Instead of waiting for hundreds of tests to execute, you can save time by running only the test(s) you’re actively working on.

In this guide, we’ll explore multiple methods to run a single test (or a subset of tests) with Mocha, including command-line flags, inline directives, and environment-specific workflows (like VS Code). Whether you’re debugging a failing test or iterating on a new feature, these techniques will help you streamline your testing workflow.

Table of Contents#

  1. Prerequisites
  2. Setting Up a Sample Mocha Project
  3. Method 1: Use .only() to Isolate Tests
  4. Method 2: --grep Flag for Matching Test Titles
  5. Method 3: Specify Test File + Line Number
  6. Method 4: --fgrep for Fixed String Matching
  7. Running Single Tests in Different Environments
  8. Common Pitfalls & Best Practices
  9. Conclusion
  10. References

Prerequisites#

Before we start, ensure you have the following:

  • Node.js & npm: Mocha runs on Node.js, so install Node.js (v14+ recommended) to get npm (Node Package Manager).
  • Basic JavaScript/Testing Knowledge: Familiarity with Mocha’s core concepts (e.g., describe blocks for test suites, it blocks for individual tests).
  • Mocha Installed: We’ll install Mocha locally in a sample project, but you can also install it globally with npm install -g mocha (optional).

Setting Up a Sample Mocha Project#

Let’s create a simple test suite to demonstrate the techniques below. Follow these steps:

Step 1: Initialize a Project#

Create a new directory and initialize npm:

mkdir mocha-single-test-demo  
cd mocha-single-test-demo  
npm init -y  

Step 2: Install Mocha#

Install Mocha as a dev dependency:

npm install --save-dev mocha  

Step 3: Create a Test File#

Create a test directory and add a test file (e.g., math.test.js):

mkdir test  
touch test/math.test.js  

Step 4: Write Sample Tests#

Paste the following code into test/math.test.js. This tests basic math operations with describe (test suite) and it (test case) blocks:

// test/math.test.js  
describe("Math Operations", () => {  
  describe("Addition", () => {  
    it("adds two positive numbers", () => {  
      const result = 2 + 3;  
      if (result !== 5) throw new Error("2 + 3 should be 5");  
    });  
 
    it("adds a positive and negative number", () => {  
      const result = 5 + (-2);  
      if (result !== 3) throw new Error("5 + (-2) should be 3");  
    });  
  });  
 
  describe("Multiplication", () => {  
    it("multiplies two numbers", () => {  
      const result = 4 * 5;  
      if (result !== 20) throw new Error("4 * 5 should be 20");  
    });  
 
    it("multiplies by zero", () => {  
      const result = 7 * 0;  
      if (result !== 0) throw new Error("7 * 0 should be 0");  
    });  
  });  
});  

Step 5: Configure the Test Script#

Update package.json to include a test script that runs Mocha:

{  
  "scripts": {  
    "test": "mocha"  
  }  
}  

Now, run all tests with:

npm test  

You’ll see output like this (4 tests total):

  Math Operations  
    Addition  
      ✔ adds two positive numbers  
      ✔ adds a positive and negative number  
    Multiplication  
      ✔ multiplies two numbers  
      ✔ multiplies by zero  

  4 passing (6ms)  

Method 1: Use .only() to Isolate Tests#

Mocha provides .only() as an inline directive to mark a test suite (describe) or test case (it) as the only one to run. This is ideal for local debugging when you want to focus on a specific test.

How It Works#

  • it.only(): Runs only the specific it block.
  • describe.only(): Runs all it blocks within the specific describe suite.

Example 1: Run a Single it Block#

Modify the it("adds two positive numbers") test in math.test.js to use it.only():

// test/math.test.js (modified)  
describe("Math Operations", () => {  
  describe("Addition", () => {  
    it.only("adds two positive numbers", () => { // Add .only() here  
      const result = 2 + 3;  
      if (result !== 5) throw new Error("2 + 3 should be 5");  
    });  
 
    // ... other tests (will be skipped)  
  });  
  // ...  
});  

Run tests again:

npm test  

Output (only 1 test runs):

  Math Operations  
    Addition  
      ✔ adds two positive numbers  

  1 passing (5ms)  

Example 2: Run an Entire describe Suite#

Use describe.only() to run all tests in a suite. For example, run only the "Multiplication" suite:

// test/math.test.js (modified)  
describe("Math Operations", () => {  
  describe("Addition", () => { /* ... */ });  
 
  describe.only("Multiplication", () => { // Add .only() here  
    it("multiplies two numbers", () => { /* ... */ });  
    it("multiplies by zero", () => { /* ... */ });  
  });  
});  

Run tests:

npm test  

Output (2 tests in the "Multiplication" suite run):

  Math Operations  
    Multiplication  
      ✔ multiplies two numbers  
      ✔ multiplies by zero  

  2 passing (6ms)  

Caveat#

Never commit .only() to version control! It will cause CI pipelines or teammates to run only that test, leading to false positives. Use .only() temporarily and remove it before committing.

Method 2: --grep Flag for Matching Test Titles#

If you prefer not to modify test files (e.g., to avoid committing .only()), use Mocha’s --grep (or -g) command-line flag. It runs tests whose titles (from it or describe blocks) match a regular expression or string.

How It Works#

  • --grep "pattern" matches test titles (it blocks) or suite titles (describe blocks) against pattern (a regex or string).
  • Mocha runs all tests/suites whose titles contain the pattern.

Example 1: Run a Test by Exact Title#

To run the it("adds two positive numbers") test, pass its title to --grep:

npm test -- --grep "adds two positive numbers"  

Output (only that test runs):

  Math Operations  
    Addition  
      ✔ adds two positive numbers  

  1 passing (5ms)  

Example 2: Run a Suite by describe Title#

To run all tests in the "Addition" suite, grep for the describe title:

npm test -- --grep "Addition"  

Output (2 tests in "Addition" run):

  Math Operations  
    Addition  
      ✔ adds two positive numbers  
      ✔ adds a positive and negative number  

  2 passing (6ms)  

Example 3: Use Regex for Flexible Matching#

--grep supports regular expressions. For example, run all tests with "multiplies" in the title:

npm test -- --grep "/multiplies/"  

Output (2 tests in "Multiplication" run):

  Math Operations  
    Multiplication  
      ✔ multiplies two numbers  
      ✔ multiplies by zero  

  2 passing (5ms)  

Tips for --grep#

  • Case Sensitivity: --grep is case-sensitive by default. Use --grep "/pattern/i" for case-insensitive matching (e.g., --grep "/Addition/i").
  • Exclude Tests: Use --invert to run tests that do not match the pattern (e.g., npm test -- --grep "Addition" --invert runs all tests except "Addition").

Method 3: Specify Test File + Line Number#

Mocha lets you run a specific test by pointing to its file path and line number. This is precise and avoids modifying test files or remembering titles.

How It Works#

Run mocha <file-path>:<line-number>, where <line-number> is the line in the test file where the it block starts.

Example#

In our math.test.js, find the line number of the it("multiplies two numbers") test. Open the file and check:

Suppose the test starts on line 15 (yours may vary—adjust based on your editor):

// Line numbers (example)  
1: describe("Math Operations", () => {  
2:   describe("Addition", () => {  
3:     it("adds two positive numbers", () => { /* ... */ });  
4:     it("adds a positive and negative number", () => { /* ... */ });  
5:   });  
6:  
7:   describe("Multiplication", () => {  
8:     it("multiplies two numbers", () => { // Line 8 (adjust to your file!)  
9:       const result = 4 * 5;  
10:      if (result !== 20) throw new Error("4 * 5 should be 20");  
11:    });  
12:    it("multiplies by zero", () => { /* ... */ });  
13:  });  
14: });  

Run the test by file and line number:

npm test -- test/math.test.js:8  

Output (only the test on line 8 runs):

  Math Operations  
    Multiplication  
      ✔ multiplies two numbers  

  1 passing (5ms)  

Note#

Line numbers can change if you edit the file (e.g., adding/removing lines above the test). Verify the line number in your editor before running.

Method 4: --fgrep for Fixed String Matching#

--fgrep (or -f) is similar to --grep but treats the pattern as a fixed string (no regex). Use this when you want to match a literal string without escaping regex characters.

Example#

Run the test with the exact title "adds a positive and negative number":

npm test -- --fgrep "adds a positive and negative number"  

Output (only that test runs):

  Math Operations  
    Addition  
      ✔ adds a positive and negative number  

  1 passing (5ms)  

This is safer than --grep if your test title contains regex special characters (e.g., ., *, ?).

Running Single Tests in Different Environments#

VS Code#

To run single tests directly in VS Code, use the Mocha Test Explorer extension (recommended):

  1. Install the Mocha Test Explorer extension.
  2. Open the Test Explorer tab (left sidebar).
  3. Expand your test suite to see individual tests. Click the "play" icon next to a test to run it.

Alternatively, configure a launch.json file to run a single test via the debugger.

Continuous Integration (CI)#

In CI pipelines (e.g., GitHub Actions, GitLab CI), use command-line flags like --grep to run specific tests. For example, to run a test titled "multiplies by zero" in CI:

Add this to your CI script (e.g., .github/workflows/test.yml for GitHub Actions):

jobs:  
  test:  
    runs-on: ubuntu-latest  
    steps:  
      - uses: actions/checkout@v4  
      - uses: actions/setup-node@v4  
      - run: npm install  
      - run: npm test -- --grep "multiplies by zero" # Run single test  

Common Pitfalls & Best Practices#

Pitfall 1: Accidentally Committing .only()#

Problem: If .only() is left in code, CI will run only that test, hiding failures in other tests.
Fix: Use a linter like eslint-plugin-mocha with the no-only-tests rule to block commits with .only().

Pitfall 2: --grep Matching Unintended Tests#

Problem: A vague pattern (e.g., --grep "add") might match multiple tests (e.g., "adds" and "addition").
Fix: Use unique, descriptive test titles (e.g., "adds two positive integers" instead of "add test").

Pitfall 3: Line Numbers Breaking After Edits#

Problem: Line numbers change when files are edited, causing mocha file.js:12 to fail.
Fix: Combine line numbers with --grep for redundancy (e.g., mocha file.js:12 --grep "specific title").

Best Practices#

  • Prefer CLI Flags Over .only(): Use --grep or line numbers to avoid modifying test files.
  • Use Unique Titles: Make test titles specific to avoid --grep collisions.
  • Test in CI: Always run the full test suite locally before pushing to ensure no .only() was left behind.

Conclusion#

Running a single test with Mocha saves time and simplifies debugging. Choose the method that best fits your workflow:

  • .only(): Quick local debugging (temporary use only).
  • --grep/--fgrep: Flexible CLI-based matching (ideal for CI or scripting).
  • File + Line Number: Precise targeting without remembering titles.

By mastering these techniques, you’ll streamline your testing process and focus on what matters: writing reliable code.

References#