Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

javascript - How can I make Mocha load a helper.js file that defines global hooks or utilities?

I have a file named test/helper.js that I use to run Mocha tests on my Node.js apps. My tests structure looks like:

test/
test/helper.js    # global before/after
test/api/sometest.spec.js
test/models/somemodel.spec.js
... more here

The file helper.js has to be loaded because it contains global hooks for my test suite. When I run Mocha to execute the whole test suite like this:

mocha --recursive test/

the helper.js file is loaded before my tests and my before hook gets executed as expected.

However, when I run just one specific test, helper.js is not loaded before the test. This is how I run it:

mocha test/api/sometest.spec.js

No global before called, not even a console.log('I WAS HERE');.

So how can I get Mocha to always load my helper.js file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Mocha does not have any notion of a special file named helper.js that it would load before other files.

What you are trying to do works when you run mocha --recursive because of the order in which Mocha happens to load your files. Because helper.js is one level higher than the other files, it is loaded first. When you specify an individual file to Mocha, then Mocha just loads this file and, as you discovered, your helper.js file is not loaded at all.

So what you want to do is load a file such that it will set top level ("global") hooks (e.g. before, after, etc.). Options:

  1. You could use Mocha programmatically and feed it the files in the order you want.

  2. You could force yourself to always specify your helper file on the command line first before you list any other file. (I would not do this, but it is possible.)

  3. Another option would be to organize your suite like I've detailed in this answer. Basically, you have one "top level" file that loads the rest of the suite into it. With this method you'd lose the ability of running Mocha on individual files, but you could use --grep to select what is being run.

You cannot use the -r option. It loads a module before running the suite but, unfortunately, the loaded module does not have access to any of the testing interface that Mocha makes available to your tests so it cannot set hooks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...