[英]How to run Mocha tests in a defined order
背景
我正在研究Node.js中的一個程序,並使用Chai和SinonJS在Mocha中編寫我的測試套件。 我有核心圖形模塊,它控制對node-webgl
上下文的訪問。
由於node-webgl
工作原理,我只希望為整個測試運行初始化一次上下文。 我想在核心模塊初始化之前運行一些測試,如下所示:
describe('module:core', function () {
describe('pre-init', function () {
describe('.isInitialized', function () {
it('should return false if the module is not initialized', function () {
expect(core.isInitialized()).to.be.false;
});
});
describe('.getContext', function () {
it('should error if no context is available', function () {
expect(function () {
core.getContext();
}).to.throw(/no context/i);
});
});
});
describe('.init', function () {
it('should error on an invalid canvas', function () {
expect(function () {
core.init(null);
}).to.throw(/undefined or not an object/i);
expect(function () {
core.init({});
}).to.throw(/missing getcontext/i);
});
it('should error if the native context could not be created', function () {
var stub = sinon.stub(global._canvas, 'getContext').returns(null);
expect(function () {
core.init(global._canvas);
}).to.throw(/returned null/i);
stub.restore();
});
it('should initialize the core module', function () {
expect(function () {
core.init(global._canvas);
}).not.to.throw();
});
});
describe('post-init', function () {
describe('.isInitialized', function () {
it('should return true if the module is initialized', function () {
expect(core.isInitialized()).to.be.true;
});
});
describe('.getContext', function () {
it('should return the current WebGL context', function () {
var gl = null;
expect(function () {
gl = core.getContext();
}).not.to.throw();
// TODO Figure out if it's actually a WebGL context.
expect(gl).to.exist;
});
});
});
});
然后我可以運行剩余的測試。
問題
當我通過Mocha運行時,一切都很好,因為核心測試套件是第一個運行的東西。 我擔心的是,如果任何測試套件在核心測試套件之前運行,那么那些測試套件將會因為核心尚未初始化而失敗。
確保核心測試套件始終在任何其他測試套件之前運行的最佳方法是什么?
最后,我重構了我的代碼以允許核心模塊被拆除而不影響node-webgl
並使用before
塊來初始化它,如下所示:
// Run this before all tests to ensure node-webgl is initialized
before(function () {
if (!global._document) {
global._document = WebGL.document();
global._document.setTitle('Machination Graphics Test Suite');
}
if (!global._canvas) {
global._canvas = global._document.createElement('canvas', 640, 480);
}
});
describe('test suite goes here', function () {
// Ensure core is ready for us before testing (except when testing core)
before(function () {
if (!core.isInitialized()) {
core.init(global._canvas);
}
});
// Tear down core after all tests are run
after(function () {
core.deinit();
});
...
});
使用before(),如文檔中所述。
describe('hooks', function() {
before(function() {
// runs before all tests in this block
});
......
});
之前的函數將首先運行,然后在其后面描述其他所有內容。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.