javascript - 使用“async-await”模式时,Mocha 单元测试未完成
问题描述
假设 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 窗口不打印摘要。它似乎挂在某个地方。
在这种情况下我做错了什么?
亲切的问候,
解决方案
我设法找到了问题所在。看来我必须关闭我的“MongoClient”连接才能让 Mocha 正确退出。
所以,我添加了一个额外的方法
public async closeAsync () : Promise<void> {
await this.client.close();
}
每次测试后都会调用此方法。
推荐阅读
- python - 每次获取字典值时执行函数的方法
- python - 你将如何使用哈希映射而不是集合来解决这个问题?
- firebase-authentication - Firebase Auth Emulator 电子邮件/密码登录 REST 端点
- reactjs - 部署 React SPA
- java - java - 如何编写一个在春季/java中工作日从上午9:30到凌晨4:00每5分钟运行一次的cron表达式?
- arrays - Powershell:空数组的条件连接分隔符(如果为空则忽略分隔符)?
- eclipse - Maven 在一个项目上失败并在另一个项目上工作
- c - 用C中的函数连接2个字符串
- java - 这个 Java 项目如何使用语言保留字作为标识符?
- python - 烧瓶前端会话是服务器端会话的副本