433

I use Mocha to test my JavaScript stuff. My test file contains 5 tests. Is that possible to run a specific test (or set of tests) rather than all the tests in the file?

Asherah
  • 18,948
  • 5
  • 53
  • 72
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

15 Answers15

493

Try using mocha's --grep option:

    -g, --grep <pattern>            only run tests matching <pattern>

You can use any valid JavaScript regex as <pattern>. For instance, if we have test/mytest.js:

it('logs a', function(done) {
  console.log('a');
  done();
});

it('logs b', function(done) {
  console.log('b');
  done();
});

Then:

$ mocha -g 'logs a'

To run a single test. Note that this greps across the names of all describe(name, fn) and it(name, fn) invocations.

Consider using nested describe() calls for namespacing in order to make it easy to locate and select particular sets.

Brandon Zacharie
  • 2,320
  • 2
  • 24
  • 29
Asherah
  • 18,948
  • 5
  • 53
  • 72
  • 6
    When using Mocha programmatically (for example from Grunt), there's a catch: grep option needs to be a ´RegExp()´ object. If it's a string, it will be escaped. – h-kippo Nov 21 '14 at 07:42
  • 1
    this is the only solution that worked for me. specifying files on the command line (`mocha some/test.js`) didn't work at all. thanks! – hraban Feb 23 '18 at 10:52
  • 2
    Any way to avoid also running `logs a bcd` which contains the `logs a` substring? Regexp `^$` not working on 0.10.2. – Ciro Santilli OurBigBook.com Oct 26 '19 at 20:26
  • Thanks.I get some errors if I don't specify directory as mocha -g 'logs a' . – kta Apr 12 '20 at 09:48
  • For any windows users: the test name needs to be double quotes, at least that is what worked for me. – Krispies Nov 30 '20 at 15:41
  • Yes it works for me ``npm run test --grep ./test/bootstrap.test.js ./test/integration/controllers/AccountManagementController-v2.test.js`` – Neel Rathod May 25 '23 at 13:13
224

Depending on your usage pattern, you might just like to use only. We use the TDD style; it looks like this:

test.only('Date part of valid Partition Key', function (done) {
    //...
}

Only this test will run from all the files/suites.

ЯegDwight
  • 24,821
  • 10
  • 45
  • 52
J Burnett
  • 2,410
  • 1
  • 13
  • 9
  • 5
    BDD works the same. This is great for when you are working on a single test. It can also be used at the suite/describe level – andyzinsser Jul 19 '13 at 02:14
  • 31
    With chai and expect syntax that would be `it.only`. – elkelk Apr 28 '16 at 14:37
  • 4
    This answer is better since it will also work when mocha is used from inside karma, etc. – Vivek Kodira Aug 09 '16 at 08:53
  • 3
    `it.only` will not work together with `given` of [mocha-testdata](https://github.com/pandell/mocha-testdata). And it's easy to forget to remove it later on. – Tr1et May 26 '17 at 02:01
  • 3
    Worth mentioning that it's easy to forget to remove `.only` when it comes to committing, which might mean only the test subset is run in CI - not good. – Greg Mar 15 '18 at 21:41
  • 6
    `eslint-plugin-mocha` has a rule `no-exclusive-tests` which will catch you if you forget to remove `.only`. – dostu May 03 '18 at 22:41
  • Dangerous if tests are are not executed via --forbid-only on the CI / build server. .only has a tendency to sneak into main branch and rendering the other tests mute as they just will not execute anymore. I came to think of the workflow of changing code to run different tests an anti-feature. The test runner should determine which tests should be executed (aka tagged tests) not the developer. – k0pernikus Mar 13 '19 at 15:02
  • 1
    @k0pernikus The question is a simple one: How do you run a single test in mocha? And the answer is a simple one: By using the `.only` method on the test (`it.only()`). As far as it being "dangerous" to do this, if a team wants to prevent only one test from running on a build server, that can and should be done by setting a code coverage threshold in a configuration file, such as `karma.conf.js`. – zumafra Dec 14 '19 at 22:08
125

If you are using npm test (using package.json scripts) use an extra -- to pass the param through to mocha

e.g. npm test -- --grep "my second test"

EDIT: Looks like --grep can be a little fussy (probably depending on the other arguments). You can:

Modify the package.json:

"test:mocha": "mocha --grep \"<DealsList />\" .",

Or alternatively use --bail which seems to be less fussy

npm test -- --bail
Ashley Coolman
  • 11,095
  • 5
  • 59
  • 81
  • 2
    @Andy `--grep ` can be a little fussy - try putting it right after mocha within the npm script entry. Else `npm test -- --bail` is useful for bailing after the first failing test – Ashley Coolman Jan 03 '17 at 16:42
  • 2
    passing extra dashes before `--grep` saved my day! Thanks a lot. PS. I'm on Windows, running `npm test -- --grep @tag` – Mykola Apr 10 '19 at 17:54
86

Just use .only before 'describe', 'it' or 'context'. I run using "$npm run test:unit", and it executes only units with .only.

describe.only('get success', function() {
 // ...
});

it.only('should return 1', function() {
  // ...
});
QauseenMZ
  • 1,081
  • 8
  • 6
35

There are multiple ways by which you can do this.

  • If you just want to run one test from your entire list of test cases then, you can write only ahead of your test case.

    it.only('<test scenario name>', function() {
      // ...
    });
    

    or you can also execute the mocha grep command as below

    mocha -g <test-scenario-name>
    
  • If you want to run all the test cases which are inside one describe section, then you can also write only to describe as well.

    describe.only('<Description of the tests under this section>', function() {
      // ...
    });
    
  • If you have multiple test files & you wanted to run only one of then you can follow the below command.

    npm test <filepath>
    

    eg :

    npm test test/api/controllers/test.js
    

    here 'test/api/controllers/test.js' is filepath.

Jitendra Pawar
  • 1,285
  • 15
  • 27
  • 1
    the `it.only()` syntax is really nifty especially if you don't want to modify your `package.json` (i.e., when the unit test runner is an aliased entry under `"scripts"`) every time you want to change the test case. more context: https://medium.com/@cnadeau_/mocha-running-a-single-test-in-dev-64f2dc509f99 – kip2 Jun 02 '21 at 19:14
35

run single test –by filename–

Actually, one can also run a single mocha test by filename (not just by „it()-string-grepping“) if you remove the glob pattern (e.g. ./test/**/*.spec.js) from your mocha.opts, respectively create a copy, without:

node_modules/.bin/mocha --opts test/mocha.single.opts test/self-test.spec.js

Here's my mocha.single.opts (it's only different in missing the aforementioned glob line)

--require ./test/common.js
--compilers js:babel-core/register
--reporter list
--recursive

Background: While you can override the various switches from the opts-File (starting with --) you can't override the glob. That link also has some explanations.

Hint: if node_modules/.bin/mocha confuses you, to use the local package mocha. You can also write just mocha, if you have it installed globally.


And if you want the comforts of package.json: Still: remove the **/*-ish glob from your mocha.opts, insert them here, for the all-testing, leave them away for the single testing:

"test": "mocha ./test/**/*.spec.js",
"test-watch": "mocha -R list -w ./test/**/*.spec.js",
"test-single": "mocha",
"test-single-watch": "mocha -R list -w",

usage:

> npm run test

respectively

> npm run test-single -- test/ES6.self-test.spec.js 

mind the -- which chains whatever text comes after it to the npm script

vsync
  • 118,978
  • 58
  • 307
  • 400
Frank N
  • 9,625
  • 4
  • 80
  • 110
  • $1 was not needed in my setup, instead, it lead to warnings like: `Warning: Could not find any test files matching pattern: $1` – Merijn Vogel Jan 13 '20 at 12:27
16

You can try "it.only"

it.only('Test one ', () => {
            
    expect(x).to.equal(y);
});

it('Test two ', () => {
            
    expect(x).to.equal(y);
});

in this the first one only will execute

Bikesh M
  • 8,163
  • 6
  • 40
  • 52
  • 2
    Dangerous if tests are are not executed via `--forbid-only` on the CI / build server. `.only` has a tendency to sneak into main branch and rendering the other tests mute as they just will not execute anymore. I came to think of the workflow of changing code to run different tests an anti-feature. The test runner should determine which tests should be executed (aka tagged tests) not the developer. – k0pernikus Mar 13 '19 at 15:01
  • I have used this for testing one functionality in my local, Note: dont commit code with `it.only` to repo – Bikesh M Mar 14 '19 at 09:25
11

Hi above solutions didn't work for me. The other way of running a single test is

mocha test/cartcheckout/checkout.js -g 'Test Name Goes here'

This helps to run a test case from a single file and with specific name.

eshwar
  • 1,763
  • 1
  • 18
  • 26
  • 2
    Use an expression that is selective enough for `-g` and you won't need to specify a file name. If you cannot write an expression that is selective enough, that means that you're not naming your tests properly. – Louis Nov 30 '16 at 11:24
9

Looking into the doc, we see that simply using:

mocha test/myfile

will work. You can omit the '.js' at the end.

Pang
  • 9,564
  • 146
  • 81
  • 122
Dave
  • 311
  • 3
  • 4
5

Using Mocha's --fgrep (or just -f) you can select tests containing string, for example:

mocha -f 'my test x'

will run all tests containing my test x in either it(), describe() or context() blocks.

Austris Cirulnieks
  • 1,099
  • 11
  • 18
4

Not sure why the grep method is not working for me when using npm test. This works though. I also need to specify the test folder for some reason.

npm test -- test/sometest.js
Pang
  • 9,564
  • 146
  • 81
  • 122
Andy N
  • 1,013
  • 9
  • 25
4

For those who are looking to run a single file but they cannot make it work, what worked for me was that I needed to wrap my test cases in a describe suite as below and then use the describe title e.g. 'My Test Description' as pattern.

describe('My Test Description', () => {
  it('test case 1', () => {
    // My test code
  })
  it('test case 2', () => {
  // My test code
  })
})

then run

yarn test -g "My Test Description"

or

npm run test -g "My Test Description"

Muhammad
  • 6,725
  • 5
  • 47
  • 54
1

Just add 'f' in front of 'it' function that run only a test where you added.

fit('should proprerly parse Enums', () => { }
viveksharma
  • 557
  • 4
  • 9
0

Consolidate all your tests in one test.js file and add a script in your package.json:

"scripts": {
  "api:test": "node_modules/.bin/mocha --timeout 10000 --recursive api_test/"
},

Type this command in your test directory:

npm run api:test
Pang
  • 9,564
  • 146
  • 81
  • 122
Shahin
  • 29
  • 3
  • in package.json, you can just use as 'mocha'. it has not to write node_modules. when you want to run on CLI, just use prefix 'npx' – cyan-kinesin Apr 30 '22 at 18:04
0

To run a single test with the following form:

//file: good.test.js
describe('describeTitle', function() {
  it('itTitle', function() {
    //some assertions
  });
});

You can run mocha like this:

mocha --grep "^describeTitle itTitle$"

And if you have multiple tests in different files that match this pattern "^describeTitle itTitle$" you can also specify the file's absolute/relative path, before --grep like this: mocha path/to/good.test.js --grep "^describeTitle itTitle$"

For example, Consider the following

describe('POST /api/products', function() {
  it('test 1', function() {
    //some assertions
  });
  it('test 2', function() {
    //some assertions
  });
});

To run test 1 you can run mocha like this:

mocha --grep "^POST /api/products test 1$"
Gandalf
  • 2,921
  • 5
  • 31
  • 44