How to run a single test with Mocha?

2019-01-12 16:20发布

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?

8条回答
forever°为你锁心
2楼-- · 2019-01-12 16:27

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 also for some reason.

npm test -- test/sometest.js

查看更多
3楼-- · 2019-01-12 16:27

Looking into https://mochajs.org/#usage we see that simply use

mocha test/myfile

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

查看更多
Anthone
4楼-- · 2019-01-12 16:29
npm test <filepath>

eg :

npm test test/api/controllers/test.js

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

查看更多
混吃等死
5楼-- · 2019-01-12 16:30

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
查看更多
Summer. ? 凉城
6楼-- · 2019-01-12 16:31

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.

查看更多
老娘就宠你
7楼-- · 2019-01-12 16:33

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.

查看更多
登录 后发表回答