首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Node中测试库

在Node中测试库
EN

Stack Overflow用户
提问于 2016-10-26 20:22:14
回答 1查看 37关注 0票数 0

我为Node写了一个图书馆。它包含多个项目可用的一堆代码。我想为它编写一些测试,使用Mocha,但是我不熟悉如何正确地测试它。

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

代码语言:javascript
复制
module.exports = {
  // properties
  connections: connections,
  // functions
  loadConnections: loadConnections,
  getDefaultConnection: getDefaultConnection,
  clearAllConnections: clearAllConnections
};

正如您可以预测的,loadConnections()验证并添加一个或多个连接作为一次,然后可以通过connections属性到达。

在我的测试文件中,我是require(databaseManager)。但是,对于每个it测试,我希望有一个“新鲜”实例来测试添加一个或多个好的或坏的配置对象。但是,要求缓存文件,以便每个测试都添加到相同的“单例”中,从而产生假阳性错误。

例如:

代码语言:javascript
复制
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属性?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-26 20:35:11

我看到的模式不是导出单个对象,而是导出用于创建唯一实例的工厂函数。例如,当您的require('express')是一个工厂函数,您可以多次调用它时,您需要吐出独立的express应用程序实例。你可以这样做:

代码语言:javascript
复制
// 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

若要使用此模式:

代码语言:javascript
复制
const myManager = require('./db-manager')();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40271492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档