Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get mocha to run my tests in isolation?

I am using mocha to run tests written using node. My assumption was that each of my tests would be isolated from each other. That does not seem to be the case. When you run mocha on a directory of tests, it appears to load all of the test files together, and then execute each of the test suites.

This can break isolation when you have modules used in one test, that can be affected by modules used in another test.

In this Gist (Failing Mocha Test) I have two modules (a and b) and two tests (a-test and b-test). If you run Mocha independently on each test they both succeed:

$ mocha --ui tdd a-test
$ mocha --ui tdd b-test

Yet, if I run these tests together, the a-test fails:

$ mocha --ui tdd .

Is it really necessary to run mocha for each individual test to get proper isolation?

Note: The reason the a-test fails is that is fires an event that calls a singleton in the b module. This does not occur in the normal execution of the b-test. Since the a-test supplies its complete set of dependencies (which does not include b), I was surprised to find all modules loaded into a single test environment.

like image 666
mckoss Avatar asked Dec 24 '15 21:12

mckoss


People also ask

Do Mocha tests run sequentially?

Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.

Does Mocha run tests in parallel?

Mocha does not run individual tests in parallel. That means if you hand Mocha a single, lonely test file, it will spawn a single worker process, and that worker process will run the file. If you only have one test file, you'll be penalized for using parallel mode.


1 Answers

If you run all the specs together in a single command, It will load all the modules into a single test environment.

Singleton pattens are generally difficult to test if you do not have the code to reset the singleton instance or create a new one when ever it is needed.

So, you probably should refactor your code. Add a reset function in a.js to reset targets = [];

Then add this to b-test.js

suiteSetup("B", function(){
    a.reset();
});

Or something like that will help.

like image 160
Anand S Avatar answered Sep 28 '22 08:09

Anand S