問題描述
我在 mocha 單元測試中使用了 expect.js 庫.目前,我需要在每個文件的第一行使用該庫,如下所示:
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
});
});
如果可能,我想從每個文件的第一行刪除樣板要求代碼,并讓我的單元測試神奇地了解 expect
.我想我可以使用 mocha.opts 文件來做到這一點:
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
但現在我在運行測試時收到以下錯誤:
But now I get the following error when running my test:
ReferenceError: 未定義期望
ReferenceError: expect is not defined
這似乎是有道理的——它怎么知道我的測試中對 expect
的引用指的是由 expect.js 庫導出的內容?
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 庫肯定會被加載,就好像我將路徑更改為不存在的東西然后 mocha 說:
The expect library is definitely getting loaded, as if I change the path to something non-existent then mocha says:
錯誤:找不到模塊'./does-not-exist.js'"
"Error: Cannot find module './does-not-exist.js'"
有什么方法可以完成我想要的嗎?如果可能有幫助的話,我正在從一個 gulp 任務中運行我的測試.
Is there any way to accomplish what I want? I'm running my tests from a gulp task if perhaps that could help.
推薦答案
您正確地需要模塊,但正如您所發現的,模塊導出的符號不會自動找到自己進入全局空間.您可以使用自己的幫助模塊來解決此問題.
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.
創建test/helper.js
:
var expect = require("expect.js")
global.expect = expect;
并將您的 test/mocha.opts
設置為:
--require test/helper
這篇關于如何從 mocha.opts 文件中正確地要求模塊的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!