2016-10-26 39 views
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屬性?

+0

可以使用鉤'before'用於建立測試環境。你可以對每個'describe'和'after'函數使用一個'before'函數來清理你的測試環境。 – Marcs

回答

0

我看到的模式不是導出單個對象,而是導出用於創建唯一實例的工廠函數。例如,當require('express')這是一個工廠函數時,您可以調用多少次來需要吐出獨立的快速應用程序實例。你可以沿着這些線路做到這一點:

// This is a function that works the same with or without the "new" keyword 
function Manager() { 
    if (!(this instanceof Manager)) { 
    return new Manager() 
    } 
    this.connections = [] 
} 

Manager.prototype.loadConnections = function loadConnections() { 
    // this.connections = [array of connections] 
} 

Manager.prototype.getDefaultConnection = function getDefaultConnection() { 
    // return this.defaultConnection 
} 
Manager.prototype.clearAllConnections = function clearAllConnections() { 
    // this.connections = [] 
} 

module.exports = Manager 

要使用此模式:

const myManager = require('./db-manager')();