用於輕鬆包裝 Mocha 測試中的 describe
、context
和 it
區塊的流暢可插拔介面。
var wrap = require('mocha-wrap');
var expect = require('chai').expect;
var mockWindow = {
location: {
href: 'test/url'
}
};
wrap().withGlobal('window', () => mockWindow).describe('mocked window', function () {
it('is mocked', function () {
expect(window).to.equal(mockWindow);
});
it('has the right URL', function () {
expect(window.location.href).to.equal('test/url');
});
});
var obj = { a: 1 };
wrap().withOverrides(() => obj, () => ({ a: 2, b: 3 })).describe('overridden object keys', function () {
it('has "b"', function () {
expect(obj.b).to.equal(3);
});
it('has overridden "a"', function () {
expect(obj.a).to.equal(2);
});
});
wrap().withOverride(() => obj, 'a', () => 4).skip().describe('this test is skipped', function () {
it('also supports .only()!', function () {
expect(true).to.equal(false); // skipped
});
});
一個 mocha-wrap
**外掛程式**是一個具名的函式,它會回傳一個 MochaWrapper 實例或是一個描述符物件。
外掛程式的函式 name
必須以字串 “with” 開頭。
外掛程式可以全域註冊,或以 ad-hoc 方式 .use
。
.use
需要一個外掛程式函式作為其第一個參數;其他參數會傳遞給外掛程式。
.extend
需要一個非空的描述字串,以及一個描述符物件,其中可能包含一個函數或一個函數陣列,這些函數的鍵對應於任何或所有受支援的 mocha 方法。
全域註冊的外掛程式、.use
呼叫和 .extend
呼叫可以鏈結、儲存和重複使用 - 鏈中的每個連結都會建立一個新的 MochaWrapper 實例。
一個描述符物件可能包含以下 5 個鍵中的任何或全部
一個 description
字串,用於 "describe" 和/或 "it" (當回傳一個物件時,這是必要的)
beforeEach
:一個函數或函數陣列,用於 mocha
beforeEach
函數
afterEach
:一個函數或函數陣列,用於 mocha
afterEach
函數
before
:一個函數或函數陣列,用於 mocha
before
函數
after
:一個函數或函數陣列,用於 mocha
after
函數
最常見的方法是讓外掛程式函數回傳 this.extend(description, descriptor)
。
外掛程式函數的 name
必須以 "with" 開頭,並將使用 MochaWrapper 實例的接收者("this" 值)來調用。
要註冊一個外掛程式,請使用外掛程式函數呼叫 mocha-wrap
上的 register
函數。這不應該在可重複使用的模組中完成。
module.exports = function withFoo(any, args, you, want) {
return this.extend('with some foo stuff', {
beforeEach: function () {
// setup ran before each test
},
afterEach: [
function () {
// teardown ran after each test
},
function () {
// more teardown
}
],
before: function () {
// setup ran once before all tests
},
after: function () {
// teardown ran once after all tests
}
});
};
var wrap = require('mocha-wrap');
wrap.register(require('mocha-wrap-with-foo'));
wrap().withFoo().describe…
雖然 mocha 具有 describe.skip
、describe.only
、context.skip
、context.only
、it.skip
和 it.only
,但如果不使用 ES5 屬性訪問器,則無法在 mocha-wrap 中實現這些。由於此專案支援 ES3,我們決定使用 .skip().describe
等,而不是放棄跳過/僅限的能力。
只需克隆儲存庫,npm install
,然後執行 npm test