在Node中测试库

时间:2016-10-26 20:22:15

标签: node.js unit-testing mocha

我有一个为Node编写的库。它包含一堆可用于多个项目的代码。我想使用Mocha为它编写一些测试,但我不熟悉如何正确测试它。

例如,名为databaseManager.js的项目中的一个文件中的代码将按如下方式导出:

module.exports = {
  // properties
  connections: connections,
  // functions
  loadConnections: loadConnections,
  getDefaultConnection: getDefaultConnection,
  clearAllConnections: clearAllConnections
};

正如您所预测的那样,loadConnections()只会验证并添加一个或多个Connections,然后可以通过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属性?

1 个答案:

答案 0 :(得分: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')();