2016-10-26 42 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')();