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
属性?
可以使用钩'before'用于建立测试环境。你可以对每个'describe'和'after'函数使用一个'before'函数来清理你的测试环境。 – Marcs