0
我有一個爲Node編寫的庫。它包含了一堆可用於多個項目的代碼。我想用Mocha寫一些測試,但我不熟悉如何正確地測試它。在節點中測試庫
例如,在項目中的一個文件中的代碼稱爲databaseManager.js
導出如下:
module.exports = {
// properties
connections: connections,
// functions
loadConnections: loadConnections,
getDefaultConnection: getDefaultConnection,
clearAllConnections: clearAllConnections
};
正如你可以預測,loadConnections()
驗證,並增加了一個或多個連接爲一次,然後可以通過以下方式聯繫connections
屬性。
在我的測試文件中,我require(databaseManager)
。但是,對於每個it
測試,我希望有一個「新鮮」實例來測試添加一個或多個好的或不好的配置對象。但是,需要緩存該文件,以便每個測試都會添加相同的「單例」,從而產生誤報錯誤。
例如:
describe('Database Manager Tests', function() {
let singleValidConfig = {
name: "postgresql.dspdb.postgres",
alias: "pdp",
dialect: "postgres",
database: "dspdb",
port: 5432,
host: "localhost",
user: "postgres",
password: "something",
primary: false,
debugLevel: 2
};
it('load 1', function() {
(function() { dbman.loadConnections(singleValidConfig, true); }).should.not.throw();
console.log('load 1', dbman);
});
it('load 2', function() {
let result = dbman.loadConnections(singleValidConfig, false);
result.should.be.true;
console.log('load 2', dbman);
});
});
一會失敗,因爲它們都添加相同配置到dbman
的一個實例,這是防不勝防。我如何確保每個it
都有乾淨的connections
屬性?
可以使用鉤'before'用於建立測試環境。你可以對每個'describe'和'after'函數使用一個'before'函數來清理你的測試環境。 – Marcs