我为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属性?
发布于 2016-10-26 20:35:11
我看到的模式不是导出单个对象,而是导出用于创建唯一实例的工厂函数。例如,当您的require('express')是一个工厂函数,您可以多次调用它时,您需要吐出独立的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')();https://stackoverflow.com/questions/40271492
复制相似问题