Javascript 如何让 Mocha 加载定义全局钩子或实用程序的 helper.js 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28191243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I make Mocha load a helper.js file that defines global hooks or utilities?
提问by Zlatko
I have a file named test/helper.jsthat I use to run Mocha tests on my Node.js apps. My tests structure looks like:
我有一个名为的文件test/helper.js,用于在我的 Node.js 应用程序上运行 Mocha 测试。我的测试结构如下所示:
test/
test/helper.js # global before/after
test/api/sometest.spec.js
test/models/somemodel.spec.js
... more here
The file helper.jshas to be loaded because it contains global hooks for my test suite. When I run Mocha to execute the whole test suite like this:
helper.js必须加载该文件,因为它包含我的测试套件的全局钩子。当我运行 Mocha 来执行整个测试套件时:
mocha --recursive test/
the helper.jsfile is loaded before my tests and my beforehook gets executed as expected.
该helper.js文件在我的测试之前加载,我的before钩子按预期执行。
However, when I run just one specific test, helper.jsis not loaded before the test. This is how I run it:
但是,当我只运行一个特定的测试时,helper.js在测试之前是不会加载的。这是我运行它的方式:
mocha test/api/sometest.spec.js
No global beforecalled, not even a console.log('I WAS HERE');.
没有全局before调用,甚至没有console.log('I WAS HERE');.
So how can I get Mocha to alwaysload my helper.jsfile?
那么如何让 Mocha始终加载我的helper.js文件呢?
采纳答案by Louis
Mocha does not have any notion of a special file named helper.jsthat it would load before other files.
Mocha 没有任何名为helper.js它会在其他文件之前加载的特殊文件的概念。
What you are trying to do works when you run mocha --recursivebecause of the order in which Mocha happensto load your files. Because helper.jsis one level higher than the other files, it is loaded first. When you specify an individual file to Mocha, then Mocha just loads this fileand, as you discovered, your helper.jsfile is not loaded at all.
你正在尝试在运行做工作mocha --recursive,因为在摩卡的顺序发生加载文件。因为helper.js比其他文件高一级,所以先加载。当您为 Mocha 指定一个单独的文件时,Mocha 只会加载这个文件,正如您发现的那样,您的helper.js文件根本没有加载。
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:
所以,你想要做的是加载的文件,以便将设置顶层(“全球”)挂钩(例如before,after等)。选项:
You could use Mocha programmaticallyand feed it the files in the order you want.
You could force yourself to always specify your helper file on the command line firstbefore you list any other file. (I would not do this, but it is possible.)
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
--grepto select what is being run.
在列出任何其他文件之前,您可以强制自己始终首先在命令行上指定您的帮助文件。(我不会这样做,但这是可能的。)
另一种选择是像我在这个答案中详述的那样组织你的套件。基本上,您有一个“顶级”文件,可以将套件的其余部分加载到其中。使用这种方法,您将失去在单个文件上运行 Mocha 的能力,但您可以使用它
--grep来选择正在运行的内容。
You cannotuse the -roption. 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.
您不能使用该-r选项。它在运行套件之前加载一个模块,但不幸的是,加载的模块无法访问 Mocha 为您的测试提供的任何测试接口,因此它无法设置挂钩。
回答by aray12
First, I would definitely use mocha.optsso that you don't have to include the options you want every time. As pointed out, one option is to use --grep, but I am not a huge fan of that personally. It required you name everything in an overly simplistic way. If the beforehook is NOT async you can use --requirein your mocha.opts. e.g.
首先,我肯定会使用,mocha.opts这样您就不必每次都包含所需的选项。正如所指出的,一种选择是使用--grep,但我个人并不喜欢它。它要求您以过于简单的方式命名所有内容。如果before钩子不是异步的,你可以--require在你的mocha.opts. 例如
#mocha.opts
--recursive
--require test/helpers.js
It sounds like this wouldn't work for you because you want global afterhook as well. What I have done is I just call the full test suite every time, but if I am in the middle of deving and only want to test one suite, or even one specific test, I use the exclusivity feature, onlyhttps://mochajs.org/#exclusive-tests. You can make it it.only('...or describe.only('...If you do this it looks through all tests and sets up exactly like your full test harness would, but then only executes the test or suite you have specified.
听起来这对你不起作用,因为你也想要全局after钩子。我所做的是每次只调用完整的测试套件,但是如果我正在开发中并且只想测试一个套件,甚至一个特定的测试,我会使用排他性功能onlyhttps://mochajs。 org/#exclusive-tests。您可以创建它,it.only('...或者describe.only('...如果您这样做,它会像完整的测试工具一样查看所有测试并进行设置,但随后仅执行您指定的测试或套件。
Now you can include those global hooks no problem. @Louis mentions that your helpers.jsare loading in the proper order only coincidently. That is not true. If you place any hooks outside of a describeblock, it automatically becomes a global hook. This can be accomplished by either putting it in its own file
现在你可以包含这些全局钩子没问题。@Louis 提到您helpers.js只是巧合地以正确的顺序加载。那不是真的。如果您在describe块之外放置任何钩子,它会自动成为全局钩子。这可以通过将它放在自己的文件中来完成
// helpers.js
before(function() { console.log('testing...'); });
or within a test file
或在测试文件中
// some.spec.js
before(function() { console.log('testing...'); });
describe('Something', function() {
it('will be tested', function() {
...
});
});
Obviously, I think putting it in its own file is cleaner. (I called it hooks.js). Point is, this is not a result of the order in which files were loaded.
显然,我认为把它放在自己的文件中更干净。(我叫它hooks.js)。重点是,这不是文件加载顺序的结果。
Just one gotcha that might be obvious to other but I struggled with briefly -- hooks not placed in a describeblock are ALL global. They are not directory specific. So if you copy helpers.jsinto a sub-directory of tests, the beforeand afterhook will now fire twice. Also, if you place a beforeEachhook in there, it will fire before every single test, not just those tests in that directory.
只是一个对其他人来说可能很明显的问题,但我曾短暂地挣扎过——没有放在describe块中的钩子都是全局的。它们不是特定于目录的。因此,如果您复制helpers.js到测试的子目录中,则beforeandafter钩子现在将触发两次。此外,如果您beforeEach在其中放置一个钩子,它将在每个测试之前触发,而不仅仅是该目录中的那些测试。
Anyway, I know this post is a bit old, but hopefully this will help others having similar issues.
无论如何,我知道这篇文章有点旧,但希望这能帮助其他有类似问题的人。
回答by Paul Redmond
What I do is create a test/test_helper.jsfile, which exports all the helpers I create:
我所做的是创建一个test/test_helper.js文件,该文件导出我创建的所有帮助程序:
// test/test_helper.js
module.exports = {
MyHelper: require('./helpers/MyHelper')
}
Then I requirethe helper on any test I need to use it:
然后我require在任何需要使用它的测试中充当助手:
// test/spec/MySpec.js
var helper = require('../test_helper');
// Or if you need just "MyHelper"
var myHelper = require('../test_helper').MyHelper;
describe('MySpec', function () {
// Tests here...
});
I prefer the above approach because its easy to understand and flexible. You can see it in action here in my demo: https://github.com/paulredmond/karma-browserify-demo/tree/master/test
我更喜欢上述方法,因为它易于理解且灵活。你可以在我的演示中看到它的实际效果:https: //github.com/paulredmond/karma-browserify-demo/tree/master/test
回答by Dave Sag
I came to this question after trying all sorts of things to get my tests to connect once to a database before subsequently running a bunch of crudtests on my models.
在尝试了各种方法让我的测试连接一次数据库之后,我来到了这个问题,然后crud在我的models.
Then I found mocha-preparewhich solved my problems.
然后我发现mocha-prepare解决了我的问题。
In your helper.jsfile you can just define a preparefunction.
在您的helper.js文件中,您可以只定义一个prepare函数。
prepare(done => {
console.log('do something asynchronously here')
done()
}, done => {
console.log('asynchronously clean up after here')
done()
})
works a treat.
很好用。
回答by daisura99
Late addition to the answer:-
迟到的答案:-
Mocha (v7.0.0 as of writing) support specifying fileas an option:-
As per the docs
Mocha(撰写时为 v7.0.0)支持指定file为选项:-
根据文档
--file Specify file(s) to be loaded prior to root suite
execution
.mocharc.json
.mocharc.json
{
"watch-files": [
"test/**/*.js"
],
"recursive": true,
"file": "test/setup"
}
./test/setup.js
./test/setup.js
const request = require('supertest');
const app = require('../app'); // express app
global.request = request(app);
A Worthy Mention:
值得一提:
I found that the above setup loaded all .jsfiles anyway, probably because of the mocha config extensionwhich is set to jsby default. Since I had the convention of naming all tests file with .spec.js, I can ignore other files by adding "ignore": ["test/**/!(*.spec.js)"]
我发现上面的设置.js无论如何都加载了所有文件,可能是因为默认extension设置为mocha 配置js。由于我有用 命名所有测试文件的约定.spec.js,我可以通过添加忽略其他文件"ignore": ["test/**/!(*.spec.js)"]
回答by Divjot Singh
In our project, we are using helpers somewhat like this:
在我们的项目中,我们使用的助手有点像这样:
clientHelper = require("../../../utils/clientHelper")
You need to configure relative path of your helper properly.
您需要正确配置助手的相对路径。
And then calling it like this:
然后像这样调用它:
clientHelper.setCompanyId(clientId)

