问题
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 :)
回答1:
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.
回答2:
Why not mocha -r <module>
or even using mocha.opts
?
Have your common file in, say, init.js
and then run
mocha -r `./init`
Which will cause mocha to run and load ./init.js
before loading any of the mocha test files.
You could also put it in mocha.opts
inside your tests directory, and have its contents be
--require ./init
来源:https://stackoverflow.com/questions/18654563/running-a-set-of-actions-before-every-test-file-in-mocha