在TypeScript中假定以下类:
class MongoDbContext implements IMongoDbContext {
private connectionString : string;
private databaseName : string;
private database : Db;
public constructor (connectionString : string, databaseName : string) {
this.connectionString = connectionString;
this.databaseName = databaseName;
}
public async initializeAsync () : Promise<MongoDbContext> {
// Create a client that represents a connection with the 'MongoDB' server and get a reference to the database.
var client = await MongoClient.connect(this.connectionString, { useNewUrlParser: true });
this.database = await client.db(this.databaseName);
return this;
}
}
现在,我想测试在尝试连接到不存在的MongoDB服务器时是否引发异常,这是通过以下集成测试完成的:
it('Throws when a connection to the database server could not be made.', async () => {
// Arrange.
var exceptionThrowed : boolean = false;
var mongoDbContext = new MongoDbContext('mongodb://127.0.0.1:20000/', 'databaseName');
// Act.
try { await mongoDbContext.initializeAsync(); }
catch (error) { exceptionThrowed = true; }
finally {
// Assert.
expect(exceptionThrowed).to.be.true;
}
}).timeout(5000);
运行此单元测试时,我的CMD窗口不显示摘要。 看来它挂在某个地方。
在这种情况下我在做什么错了?
亲切的问候,
答案 0 :(得分:0)
我设法找到了问题。 看来我必须关闭“ MongoClient”连接才能使Mocha正确退出。
所以,我添加了一个额外的方法
public async closeAsync () : Promise<void> {
await this.client.close();
}
每次测试后都会调用此方法。