How to specify test directory for mocha?

后端 未结 14 1484
走了就别回头了
走了就别回头了 2020-12-04 05:59

Mocha tries to find test files under test by default, how do I specify another dir, e.g. server-test?

相关标签:
14条回答
  • 2020-12-04 06:33

    As mentioned by @superjos in comments use

    mocha --recursive "some_dir"

    0 讨论(0)
  • 2020-12-04 06:36

    The nice way to do this is to add a "test" npm script in package.json that calls mocha with the right arguments. This way your package.json also describes your test structure. It also avoids all these cross-platform issues in the other answers (double vs single quotes, "find", etc.)

    To have mocha run all js files in the "test" directory:

    "scripts": {
        "start": "node ./bin/www", -- not required for tests, just here for context
        "test": "mocha test/**/*.js"
      },
    

    Then to run only the smoke tests call:

    npm test
    

    You can standardize the running of all tests in all projects this way, so when a new developer starts on your project or another, they know "npm test" will run the tests. There is good historical precedence for this (Maven, for example, most old school "make" projects too). It sure helps CI when all projects have the same test command.

    Similarly, you might have a subset of faster "smoke" tests that you might want mocha to run:

    "scripts": {
        "test": "mocha test/**/*.js"
        "smoketest": "mocha smoketest/**/*.js"
      },
    

    Then to run only the smoke tests call:

    npm smoketest
    

    Another common pattern is to place your tests in the same directory as the source that they test, but call the test files *.spec.js. For example: src/foo/foo.js is tested by src/foo/foo.spec.js.

    To run all the tests named *.spec.js by convention:

      "scripts": {
        "test": "mocha **/*.spec.js"
      },
    

    Then to run all the tests call:

    npm test
    

    See the pattern here? Good. :) Consistency defeats mura.

    0 讨论(0)
提交回复
热议问题