Reputation: 1179
I have a set of mocha test scripts (= files), located in /test together with mocha.opts. It seems mocha is running all test files in parallel, is this correct? This could be a problem if test data are used in different test scripts. How can I ensure, that each file is executed separately?
Upvotes: 0
Views: 1128
Reputation: 46
Be careful when assigning environment variables outside of mocha hooks since the assignments to that variables are done in all files before any test execution (i.e eny "before*"
or "it"
hook).
Hence the value assigned to the environment variable in the first file will be overwritten in the second one, before any Mocha test hook execution.
Eg. if you are assigning process.env.PORT=5000
in test1.js
file and process.env.PORT=6000
in test2.js
outside of any mocha hook, then when the tests from test1.js
starts execution the value of the process.env.PORT
will be 6000
and not 5000
as you may expect.
Upvotes: 0
Reputation: 151411
It seems mocha is running all test files in parallel, is this correct?
No.
By default, Mocha loads the test files sequentially, and records all tests that must be run, then it runs the test one by one, again sequentially. Mocha will not run two tests at the same time, no matter whether the tests are in the same file or in different files. Note that whether your tests are asynchronous or synchronous makes no difference: when Mocha starts an asynchronous test, it waits for it to complete before moving on to the next test.
There are tools that patch Mocha to run tests in parallel. So you may see demonstrations showing Mocha tests running in parallel, but this requires additional tools, and is not part of Mocha properly speaking.
If you are seeing behavior that suggest tests running in parallel, that's a bug in your code, or perhaps you are misinterpreting the results you are getting. Regarding bugs, it is possible to make mistakes and write code that will indicate to Mocha that your test is over, when in fact there are still asynchronous operations running. However, this is a bug in the test code, not a feature whereby Mocha is running tests in parallel.
Upvotes: 2