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

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

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

In this Gist ( Failed Mocha Test ) I have two modules (a and b) and two tests (a-test and b-test). If you run Mocha independently of each test, they are both successful:

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

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

 $ mocha --ui tdd . 

Do you really need to run mocha for each individual test to get proper insulation?

Note. The reason for the failure of the a-test is that it raises an event that raises a singleton in module b. This does not occur during normal b-test execution. Since the a-test provides a complete set of dependencies (which does not include b), I was surprised to find that all modules are loaded into the same test environment.

+5
source share
1 answer

If you run all the specifications together in one command, it will load all the modules in one test environment.

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

So, you probably have to reorganize your code. Add the reset function to a.js in reset targets = [];

Then add this to b-test.js

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

Or something like that will help.

+2
source

Source: https://habr.com/ru/post/1239166/


All Articles