問題描述
我在 mocha 單元測試中使用了 expect.js 庫.目前,我需要在每個(gè)文件的第一行使用該庫,如下所示:
I'm using the expect.js library with my mocha unit tests. Currently, I'm requiring the library on the first line of each file, like this:
var expect = require('expect.js');
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
如果可能,我想從每個(gè)文件的第一行刪除樣板要求代碼,并讓我的單元測試神奇地了解 expect
.我想我可以使用 mocha.opts 文件來做到這一點(diǎn):
If possible, I'd like to remove the boilerplate require code from the first line of each file, and have my unit tests magically know about expect
. I thought I might be able to do this using the mocha.opts file:
--require ./node_modules/expect.js/index.js
但現(xiàn)在我在運(yùn)行測試時(shí)收到以下錯(cuò)誤:
But now I get the following error when running my test:
ReferenceError: 未定義期望
ReferenceError: expect is not defined
這似乎是有道理的——它怎么知道我的測試中對 expect
的引用指的是由 expect.js 庫導(dǎo)出的內(nèi)容?
This seems to make sense - how can it know that the reference to expect
in my tests refers to what is exported by the expect.js library?
expect 庫肯定會(huì)被加載,就好像我將路徑更改為不存在的東西然后 mocha 說:
The expect library is definitely getting loaded, as if I change the path to something non-existent then mocha says:
錯(cuò)誤:找不到模塊'./does-not-exist.js'"
"Error: Cannot find module './does-not-exist.js'"
有什么方法可以完成我想要的嗎?如果可能有幫助的話,我正在從一個(gè) gulp 任務(wù)中運(yùn)行我的測試.
Is there any way to accomplish what I want? I'm running my tests from a gulp task if perhaps that could help.
推薦答案
您正確地需要模塊,但正如您所發(fā)現(xiàn)的,模塊導(dǎo)出的符號(hào)不會(huì)自動(dòng)找到自己進(jìn)入全局空間.您可以使用自己的幫助模塊來解決此問題.
You are requiring the module properly but as you figured out, the symbols that the module export won't automatically find themselves into the global space. You can remedy this with your own helper module.
創(chuàng)建test/helper.js
:
var expect = require("expect.js")
global.expect = expect;
并將您的 test/mocha.opts
設(shè)置為:
--require test/helper
這篇關(guān)于如何從 mocha.opts 文件中正確地要求模塊的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!