Explain Codes LogoExplain Codes Logo

How to run a single test with Mocha?

javascript
test-engineering
mocha
testing-best-practices
Alex KataevbyAlex Kataev·Oct 16, 2024
TLDR

In Mocha, you can run a single test by chaining it or describe with only:

describe('Test Suite', function() { it.only('runs this test only', function() { // Your test code // It's like saying: "You're the ONE. It's always been you!" }); }); describe.only('Enjoy My Test Suite - final destination of your bugs', function() { // everything related to your tests });

Calling only makes sure that just the chosen test or test suite will run.

Additionally, Mocha offers the --grep flag for running particular tests without changing your test code:

mocha --grep "keyword from your test name"

Now, let's explore in detail how to effectively use these features and fine-tune your testing strategy with Mocha.

Parsing through the pile with --grep

The --grep flag in Mocha is like a search function for your tests. Here's how to use it:

  • Pattern matching: The --grep option takes a string or regular expression that matches the titles of describe or it blocks.
  • Organizing and Finding: Structure your tests with nested describe() calls, creating a nicely organized namespace hierarchy. Finding and running related tests is easy when you can target a namespace with --grep.
  • Package.json: Set up scripts for commonly run tests in your package.json. This way, you don't have to remember long command lines every time you run your tests.

Making npm work for you

When running tests with npm, you'll need to pass --grep as follows:

npm test -- --grep "unique part of your test name"

Edit your scripts in package.json to run these commands with ease.

Efficient testing

  • Ensure test coverage: Don't let your use of .only() impede your testing. Always remove all .only calls before pushing your code.
  • Fail fast with --bail: Want to save some time? Use --bail to stop after the first fail, thus swiftly identifying where things went wrong.

Organizing your tests

  • Clear structure: Lay out your tests thoughtfully from the get-go. This makes it easier to use both --grep and .only.
  • Don't lose focus: Use test.only() when developing a new feature or during bug-fixing to focus on what you're working on.

When things don't go as planned

Sometimes, --grep may not act as expected. This typically happens due to:

  • Overly complex patterns: When regular expressions become too fancy, they can match more than intended. Keep them as simple as possible.
  • Glob Patterns conflict: If a glob pattern is included in mocha.opts or in the Mocha command, it may interfere with your --grep pattern. Be mindful to avoid headaches.