首页 > 解决方案 > 使用“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 窗口不打印摘要。它似乎挂在某个地方。

在这种情况下我做错了什么?

亲切的问候,

标签: javascripttypescriptmocha.jschai

解决方案


我设法找到了问题所在。看来我必须关闭我的“MongoClient”连接才能让 Mocha 正确退出。

所以,我添加了一个额外的方法

public async closeAsync () : Promise<void> {
    await this.client.close();
}

每次测试后都会调用此方法。


推荐阅读