I've started recently working with mocha to test my expressjs server. My tests are separated to multiple files and most of them contain some duplicated segments (Mostly before statements that load all the fixtures to the DB, etc) and that's really annoying.
I guess I could export them all to a single file and import them on each and every test, but I wonder if there are some more elegant solutions - such as running a certain file that has all the setup commands , and another file that contains all the tear-down commands.
If anyone knows the answer that would be awesome :)
Your tests will run in the given order.
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. Don't do that.
beforeEach() HooksIn a test file, the function beforeEach() will be executed before each test. beforeEach() is often used to set up or reset code, like variables and values, for other function calls to use in their execution.
There are three basic levels of factoring out common functionality for mocha tests. If you want to load in some fixtures once for a bunch of tests (and you've written each test to be independent), use the before
function to load the fixtures at the top of the file. You can also use beforeEach
function if you need the fixtures re-initialized each time.
The second option (which is related), is to pull out common functionality into a separate file or set of files and require that file.
Finally, note that mocha has a root level hook:
You may also pick any file and add "root"-level hooks. For example, add beforeEach() outside of all describe() blocks. This will cause the callback to beforeEach() to run before any test case, regardless of the file it lives in (this is because Mocha has an implied describe() block, called the "root suite").
We use that to start an Express server once (and we use an environment variable so that it runs on a different port than our development server):
before(function () {
process.env.NODE_ENV = 'test';
require('../../app.js');
});
(We don't need a done()
here because require is synchronous.) This was, the server is started exactly once, no matter how many different test files include this root-level before
function.
The advantage of splitting things up in this way is that we can run npm test
which runs all tests, or run mocha on any specific file or any specific folder, or any specific test or set of tests (using it.only and describe.only) and all of the prerequisites for the selected tests will run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With